【发布时间】:2018-12-22 09:10:27
【问题描述】:
我将这个帖子请求从我的index.js 发送到我的app.js(在点击事件上):
var data = {
name: "Sarah",
age: "21"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", "/", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
data: data
}));
然后在我的app.js,我有这个:
app.post('/', function(req, res) {
if(req.xhr) {
console.log(req.body.name);
}
});
但是过了一会儿,控制台什么也没有记录?我也安装了body-parser。有什么遗漏吗?
一段时间后,我也在控制台中收到此错误消息:
POST http://localhost:8080/ 0 ()
【问题讨论】:
-
您没有发送回复?
res.end()。或发送状态码。 -
我猜应该是
req.body.data.name。还有res.send()也是需要的 -
你可以通过sn -p
console.log(req.body);查看req.body对象,然后你可以看到body对象没有任何名为name的字段,body只有一个字段 -data。另一种方式,您在客户端进行更改xhr.send(JSON.stringify(data); -
添加 res.send() 有效。谢谢@dhilt
标签: javascript node.js express post xmlhttprequest