【问题标题】:POST request body is empty on server服务器上的 POST 请求正文为空
【发布时间】:2020-02-10 08:04:13
【问题描述】:

我正在尝试使用 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);
    });
});

【问题讨论】:

  • 添加bodyparser节点模块
  • Abhishek,我已经添加了 body-parser 模块。
  • 它应该在所有路线之上。可以贴代码吗?
  • urlencodedParser 是做什么的?没有它你可以试试吗?
  • Abhishek,我认为 body-parser 模块没有问题。当我使用 JQuery 发出 AJAX 请求时,该应用程序运行良好。当我切换到 XMLHttpRequest API 时,它停止了工作。

标签: javascript node.js ajax post xmlhttprequest


【解决方案1】:

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 的默认行为。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2020-01-09
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2016-06-01
    • 2021-02-12
    • 1970-01-01
    • 2016-04-02
    相关资源
    最近更新 更多