NodeJS 发送POST请求,以更简单的方式评估按钮A或B是否被按下?

vltsax25  于 2023-01-01  发布在  Node.js
关注(0)|答案(1)|浏览(100)

服务器端:

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");
    }
});

客户端:

<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>

是否有更简单的方法来评估按钮A或B是否被按下?

  • 我在考虑省略值定义,只检查按钮A或B的post请求?有人知道如何安排吗?正文或http头是否包含发送它的对象名称(按钮A或B)?
qaxu7uf2

qaxu7uf21#

将相同的name与不同的value配合使用:

<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>

那么你需要评估的就是

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

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;
    }
});

相关问题