单击复选框后未获取req.body.task [英] get req.body.task is undefined after click on checkbox
问题描述
当我单击复选框时,然后req.body.task 返回未定义
.
When I have click on checkbox then req.body.task return undefined
.
<input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})">
执行更改功能,返回已选中或未选中复选框的ID.
Perform on change function which return id of checked or unchecked checkbox.
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模板引擎把手
Working with expressJS nodeJs template engine handlebars
推荐答案
您发送ID的方式不正确.
The way you are sending id is not correct.
您需要做的是绑定您的onclick事件处理函数,并使用该事件获取ID或值,无论您需要在事件处理函数中使用什么.另外,您正在将id设置为名为global的键,但是您正在使用req.body.task进行访问,这是不正确的.
What you need to do is bind your onclick event handler function and with that event get id or value whatever you need in the event handler function. Also you are setting id to a key called global but you are accessing with req.body.task which is not correct.
Workig代码位于代码沙箱
Workig code is available in codesandbox
检查以下代码,以更好地了解如何在路由器中发送ID和访问ID.
Check below code for better understanding of how to send id and access the id in router.
<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);
});
这篇关于单击复选框后未获取req.body.task的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!