首页 > 解决方案 > 单击复选框后获取 req.body.task 未定义

问题描述

当我点击复选框然后 req.body.task return undefined

<input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})">

执行更改功能,返回选中或未选中复选框的 id。

function onToDochange(id) {
    // console.log(id);
    fetch('/checkbox', {
       method: 'POST',
       body: JSON.stringify({global: id})
     })
    .then(res=>res.json())
    .then(res => console.log(res));
};

路由

app.post('/checkbox', (req, res) => {
    console.log(req.body.task);
});

使用 expressJS nodeJs 模板引擎把手

标签: javascriptnode.jsexpressbody-parser

解决方案


您发送 id 的方式不正确。

您需要做的是绑定您的 onclick 事件处理函数,并使用该事件获取事件处理函数中所需的 id 或值。此外,您将 id 设置为一个名为 global 的键,但您正在使用不正确的 req.body.task 访问。

工作代码在代码沙箱中可用

检查下面的代码以更好地了解如何发送 id 和访问路由器中的 id。

<input type="checkbox" name="task" autocomplete="off" checked="" onclick='onToDochange(this)' value="task" id="2">


function onToDochange(event) {
    // console.log(event.id);
    fetch('/checkbox', {
       method: 'POST',
       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json'
       },
       body: JSON.stringify({"id": event.id})
     })
    .then(res=>res.json())
    .then(res => console.log(res));
};

路由

app.post('/checkbox', (req, res) => {
    console.log(req.body.id);
});

推荐阅读