简体   繁体   English

req.body 是一个空的 object,表示

[英]req.body is an empty object, express

Im sending a request to my local server in my react app like this我像这样在我的反应应用程序中向我的本地服务器发送请求

  fetch("http://localhost:4000/signup", {
  method: "POST",
  mode: "no-cors",
  body: JSON.stringify({ name: "Joe", lname: "Doe" }),
  headers: {
    "Content-Type": "application/json",
  },
})

And the problem is that im getting empty object on the req.body on my local server.问题是我在本地服务器上的 req.body 上得到了空的 object。

app.post('/signup', (req, res) => {
console.log(req.body);
console.log('post request sent');

}) })

How could i fix it that i could see the content which is being sent from the fetch body?我怎样才能修复它,我可以看到从 fetch 正文发送的内容?

You appear to have two problems here each of which, by themselves, would cause the symptoms you describe.您在这里似乎有两个问题,每个问题本身都会导致您描述的症状。

First, as per the documentation for req.body :首先,根据req.body的文档:

Contains key-value pairs of data submitted in the request body.包含在请求正文中提交的数据键值对。 By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().默认情况下,它是未定义的,并且在您使用诸如 express.json() 或 express.urlencoded() 之类的正文解析中间件时填充。

You don't seem to have loaded the JSON body-parsing middleware.您似乎没有加载 JSON 正文解析中间件。

Second, you said mode: "no-cors" which tells fetch to silently ignore any attempts to do anything which would require permission from CORS.其次,您说mode: "no-cors"告诉fetch默默地忽略任何需要 CORS 许可的尝试。

This includes setting the Content-Type: application/json header which is needed to trigger the JSON parsing middleware.这包括设置Content-Type: application/json header ,这是触发 JSON 解析中间件所需的。

So remove mode: "no-cors" and add the cors middleware to your server-side code.所以删除mode: "no-cors"并将cors中间件添加到您的服务器端代码中。

use axios for api request and try this hope so it will work对 api 请求使用 axios 并尝试这个希望它会起作用

const data= { name:'zafar',lname:"niazi" };常量数据= {名称:'zafar',lname:“niazi”};

axios.post('https://localhost:4000/signup', data) axios.post('https://localhost:4000/signup', 数据)

.then(data){ .then(数据){

console.log(data);控制台.log(数据); }); });

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

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