简体   繁体   English

我如何阻止 req.body 为空。 node.js 快递

[英]how do i stop req.body from being empty. node.js express

I have a simple express app that gets one fetch request, the fetch looks like this:我有一个简单的快速应用程序,它获取一个获取请求,获取看起来像这样:

let opts = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  mode: "no-cors",
  body: {
    "test": "test"
  }
}

fetch("http://localhost:3001/data", opts)

and it's in the setup() function.它在 setup() function 中。

the serverside code looks like this:服务器端代码如下所示:

const express = require('express');
const app = express();
app.listen(3001, () => console.log("listening at 3001"));
app.use(express.static("public"));
app.use(express.json());

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

in my console what I get after refreshing everything is this:在我的控制台中,我刷新所有内容后得到的是:

listening at 3001
post recived
{}

the body of the post is not undefined but it is empty, I cannot figure out what the problem is for the life of me帖子的正文不是未定义的,而是空的,我无法弄清楚我一生的问题是什么

Problem one: no-cors问题一:无cors

mode: "no-cors", is a declaration that you are not going to do anything which requires permission from CORS and that any CORS related errors should be suppressed. mode: "no-cors",是一个声明,你不会做任何需要 CORS 许可的事情,并且任何与 CORS 相关的错误都应该被抑制。

You need permission from CORS in order to set an application/json content-type header.需要CORS 的许可才能设置application/json内容类型 header。

So the first job is to remove that line .所以第一项工作是删除那条线


Problem two: CORS问题二:CORS

Then you need to change the server so it grants you permission to make the request.然后您需要更改服务器,以便它授予您发出请求的权限。

Install the cors middleware package and follow the setup instructions there.安装cors中间件 package并按照那里的设置说明进行操作。

Make sure you enable support for preflight requests because setting an application/json content-type header requires a preflight.确保启用对预检请求的支持,因为设置application/json内容类型 header 需要预检。


Problem three: JSON问题三:JSON

You claim you are sending JSON, but you are passing fetch a plain object.您声称您正在发送 JSON,但您正在传递fetch一个普通的 object。

When you do that, fetch will convert it to a string using the built-in toString method.当您这样做时, fetch将使用内置的toString方法将其转换为字符串。 This gives you "[object Object]" which is not JSON and doesn't contain your data.这为您提供了"[object Object]" ,它不是 JSON 并且不包含您的数据。

You need to pass JSON instead.您需要改为通过 JSON 。

body: JSON.stringify({
   "test": "test"
})

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

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