单击复选框后,get req.body.task 未定义

get req.body.task is undefined after click on checkbox

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

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

执行 return 已选中或未选中复选框 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 模板引擎把手

您发送 id 的方式不正确。

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

Workig 代码在 codesandbox

中可用

检查下面的代码以更好地理解如何在路由器中发送 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);
});