【问题标题】:body empty while sending HTTP POST request from JavaScript to node server从 JavaScript 向节点服务器发送 HTTP POST 请求时正文为空
【发布时间】:2021-10-18 03:08:01
【问题描述】:

我正在从 javascript 向我的节点服务器发出 XMLHttprequest。

这是我的要求:

        var data = { "fname": "Fasal", "lname": "Rahman" };
        var body = JSON.stringify(data);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/admin");
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(body);

这是我的帖子:

app.post("/admin", function(req, res) {
   console.log(req.body);
});

我正在使用正文解析器

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));

我从服务器请求中得到的正文是这样的

{ '{"fname":"Fasal","lname":"Rahman"}': '' }

整个body json为key,value为''

我需要正文在这样的键值对中 {fname:"Fasal",lname:"Rahman"}

发送 JSON 对象的正确方法是什么?

【问题讨论】:

  • 您的方法似乎是 POST,但您的处理程序是 get。
  • 抱歉,我提出问题时输入错误,编辑了问题。
  • 为什么要将 Content-type 标头设置为 application/json 以外的内容?
  • var data = { fname: "Fasal", lname: "Rahman" };

标签: javascript node.js web npm


【解决方案1】:

您的 Content-type 标头应为“application/json”:

const data = { "fname": "Fasal", "lname": "Rahman" };
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "/admin");
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify(data));

【讨论】:

  • 当我这样做时得到空对象{ }
  • 怀疑你的body解析。如果你有 Express 4.16+,你可以使用app.use(bodyParser.json()) 或简单的app.use(express.json());
猜你喜欢
  • 2015-12-11
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 2017-05-04
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多