服务器上的POST请求正文为空

时间:2019-10-13 13:52:08

标签: javascript node.js ajax post xmlhttprequest

我正在尝试使用XMLHttpRequest从客户端javascript发出AJAX请求。以下是它的代码:

document.getElementById('myform').onsubmit=function(){
    var http = new XMLHttpRequest();
    var text = document.getElementById('myinput').value;
    console.log(text);
    http.onreadystatechange = function(){
        if(http.readyState === 4 && http.status === 200){
            location.reload();
        }
    };
    http.open('POST','/todo',true);
    http.setRequestHeader("Content-Type", "application/json");
    var obj = {
        item:text
    };
    http.send(JSON.stringify(obj));
}

这正常工作,没有出现anny错误。但是,在服务器端,当我尝试将请求正文记录到控制台时,它显示为空对象。有人可以帮我弄这个吗?以下是用于处理发布请求的服务器端代码:

app.post('/todo',urlencodedParser, function(req,res){
    console.log(req.body); // This logs an empty object to the console!
    newItem = Todo(req.body);
    newItem.save(function(err,data){
        if(err) throw err;
        res.json(data);
    });
});

1 个答案:

答案 0 :(得分:0)

JSON编码和URL编码不同。

如果您希望使用JSON编码发送数据,则必须使用适当的中间件来接收数据:

const bodyParser = require('body-parser');

app.post('/todo', bodyParser.json(), function(req,res){
    console.log(req.body); // This logs an empty object to the console!
    newItem = Todo(req.body);
    newItem.save(function(err,data){
        if(err) throw err;
        res.json(data);
    });
});

它最有可能与jQuery一起使用,因为urlencoding是$.post的默认行为。

相关问题