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

Javascript 服务器上的POST请求正文为空,javascript,node.js,ajax,post,xmlhttprequest,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

我试图使用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));
}
这样做很好,没有明显的错误。但是,在服务器端,当我尝试将请求主体记录到控制台时,它显示为一个空对象。有人能帮我吗?以下是处理post请求的服务器端代码:

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

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

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

添加bodyparser节点模块Hishek,我已经添加了body parser模块。它应该位于所有路由之上。你能粘贴代码吗?urlencodedParser做什么?你能试试没有它吗?阿披舍克,我认为身体解析器模块没有问题。当我使用JQuery发出AJAX请求时,该应用程序运行良好。当我切换到XMLHttpRequestAPI时,它停止工作。添加bodyparser节点moduleAbhishek,我已经添加了body parser模块。它应该位于所有路由之上。你能粘贴代码吗?urlencodedParser做什么?你能试试没有它吗?阿披舍克,我认为身体解析器模块没有问题。当我使用JQuery发出AJAX请求时,该应用程序运行良好。当我切换到XMLHttpRequestAPI时,它停止了工作。