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

自闭症网瘾萝莉.ら 提交于 2019-12-14 03:27:30

问题


When I have click on checkbox then req.body.task return undefined.

<input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{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));
};

Routing

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

Working with expressJS nodeJs template engine handlebars


回答1:


The way you are sending id is not correct.

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 code is available in codesandbox

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

Routing

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


来源:https://stackoverflow.com/questions/52423667/get-req-body-task-is-undefined-after-click-on-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!