Home > Back-end >  Sending a POST request, evaluating if button A or B is pressed in a more simple way?
Sending a POST request, evaluating if button A or B is pressed in a more simple way?

Time:12-29

Server Side:

app.post('/', (req, res) => {
    if (req.body.buttonA == 'buttonA'){
        console.log("Button A pressed");
        
    } else if (req.body.buttonB == 'buttonB'){
        console.log("Button B pressed");
    }
});

Client Side:

        <form method="POST" action="/">
            <button type="submit" name="buttonA" value="buttonA">Button A</button>
            <button type="submit" name="buttonB" value="buttonB">Button B</button>
        </form>

Is there a more simple way of evaluating if Button A or B is pressed?

  • Iam thinking about omitting the value definitions and just checking if its a post request by button A or B? Does somebody know how to arrange that? Does the body or the http header contain the objectname (Button A or B) which it is sent from?

CodePudding user response:

Use the same name with different values:

<form method="POST" action="/">
    <button type="submit" name="button" value="A">Button A</button>
    <button type="submit" name="button" value="B">Button B</button>
</form>

Then all you need to evaluate is

app.post('/', (req, res) => {
    console.log(`Button ${req.body.button} pressed`);
});

or

app.post('/', (req, res) => {
    const { button } = req.body;
    switch(button) {
        case 'A':
        case 'B':
            console.log(`Button ${button} pressed`);
            break;
        default:
            console.log(`Unknown button ${button}`);
            break;
    }
});
  • Related