Home > Net >  How to get value of button on button click in node js?
How to get value of button on button click in node js?

Time:03-13

I am working on a form in React which POST the value of the button when clicked. But I am not able to find any solution to this, how I can get that value at the current URL and access it at the backend. Here is my code from the react js file :

              <form action='http://localhost:5000/api/button' method='POST'>
              <button value = "firstButton"  type = "submit" className='btn' name = "clickBtn" onClick={handleClick()}>Click It</button>
              

              <button value = "secondButton"  type = "submit" className='btn' name = "clickBtn" onClick={handleClick()}>Click It</button>

              
              <button value = "thirdButton"  type = "submit" className='btn' name = "clickBtn" onClick={handleClick()}>Click It</button>
              </form>

Here is the code from my node js file :

const value = req.body;
console.log("Button clicked has value: " value.value)

CodePudding user response:

req.body isn't populated until you tell the app to use a parser.

Use this middleware to parse your incoming request body as a urlencoded string

app.use(
    express.urlencoded({
      extended: true
    })
)

CodePudding user response:

Using useStates to store the values of your inputs can work! then submit that to the API

axios.post('http://localhost:5000/api/button', data);

https://www.w3schools.com/react/react_forms.asp

  • Related