'how to tell which button was clicked in post request with node backend

I have a node application, where on the frontend, I have multiple buttons that activate the same post route as specified by the formaction attribute below:

<button type="submit" formaction="/specifiedroute">-</button>

However, I want to be able to tell which button was clicked within the post route. Is there anyway I would be able to access the name or id attributes of the button within the post route (perhaps within the request object)? If not, would the only way to identify the buttons be to add a parameter to the formaction as below:

<button type="submit" formaction="/specifiedroute?redbutton">-</button>

Note all these buttons exist in one form (I can't change this) and I can't just use a hidden input field.



Solution 1:[1]

May be you should try this

<button type="submit" formaction="/specifiedroute?button=red">Red</button>
<button type="submit" formaction="/specifiedroute?button=green">Green</button>
<button type="submit" formaction="/specifiedroute?button=blue">Blue</button>

// NodeJS

Controller

app.post('/specifiedroute', (req, res) => {
  let buttons = {
    "red": "Red Button Clicked",
    "green": "Green Button Clicked",
    "blue": "Blue Button Clicked"
  }
  let reqButton = req.query.button;
  res.send(buttons[reqButton])
})

Solution 2:[2]

The name and value of the submit button used to submit a form will be included in the submitted form data.

<button formaction="/specifiedroute" name="foo" value="minus">-</button>

and on the server

if (req.body.foo === 'minus')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Quentin