简体   繁体   English

为什么 req.body 返回一个空的 object?

[英]why is req.body returning an empty object?

As the title states req.body is printing out an empty object or {}.正如标题所述,req.body 打印出一个空的 object 或 {}。 I have looked at a few other posts and can see this is a common problem but none of the posted solutions that I have found have fixed the problem.我查看了其他一些帖子,发现这是一个常见问题,但我发现的已发布解决方案均未解决该问题。

client side code客户端代码

 const myData = "hello world";
  const options = {
    method: "POST",
    header: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(myData),
  };
  fetch("http://localhost:8000/api", options);

server side node.js code服务器端 node.js 代码

app.use(express.json({ limit: "1000mb" }));
app.use(express.urlencoded({ limit: "1000mb", extended: true }));

app.listen(8000, function () {
  console.log("server is running");
});

app.use(express.static("public"));

app.post("/api", (req, res) => {
  console.log(req.body);
});

edit: I believe body-parser has been a part of express for a while now and express implements its own version of body parser through编辑:我相信 body-parser 已经成为 express 的一部分,并且 express 通过

app.use(express.json({ limit: "1000mb" }));
app.use(express.urlencoded({ limit: "1000mb", extended: true }));

You have two problems.你有两个问题。

Headers标头

Your immediate problem is that you made a typo.你的直接问题是你打错了字。 The option name you need to pass to fetch is headers (plural) not header .您需要传递给fetch的选项名称是headers (复数)而不是header

Since you failed to say you were sending JSON, you bypassed the JSON parsing middleware entirely.由于您没有说您正在发送 JSON,因此您完全绕过了 JSON 解析中间件。

Modern JSON现代 JSON

The current JSON specification allows a JSON text to consist of any JSON data type.当前的 JSON 规范允许 JSON 文本包含任何 JSON 数据类型。

The original specification only allowed the top level to be an object or an array.原始规范只允许顶层是 object 或数组。

The middleware you are using enforces the original specification by default, so trying to send a string as your entire JSON text will throw an exception.您使用的中间件默认执行原始规范,因此尝试将字符串作为整个 JSON 文本发送将引发异常。

To allow strings set strict :允许字符串设置strict

app.use(express.json({ limit: "1000mb", strict: false }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM