简体   繁体   English

无法将来自 HTTP 发布请求的数据传递给 javascript(expressjs) controller

[英]Not able to pass data from HTTP post request to the javascript(expressjs) controller

I am using react at the frontend and expressjs at the backend.我在前端使用 react,在后端使用 expressjs。 Creating a simple post request and passing json data to the back end via the front end.创建一个简单的 post 请求并通过前端将 json 数据传递到后端。 THe request consist of body{title:"some title", content:"some content"}.请求由 body{title:"some title", content:"some content"} 组成。 In the back end if I console.log(req.body), I am getting an empty object.在后端,如果我 console.log(req.body),我得到一个空的 object。 Also If i use postman it works correctly.此外,如果我使用 postman 它可以正常工作。 Front end Code:前端代码:

fetch(url, {
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: postData.title,
        content: postData.content
      })
    })

BackEnd code:后端代码:

const title = req.body.title;
  const content = req.body.content;
  console.log(req);
  res.status(201).json({
    message: 'created nicely',
    post: {
      _id: '78',
      title: title,
      content: content,
      creator: { name: 'mera naam' },
      createdAt: new Date()
    }
  });

The header property should be headers . header属性应该是headers

fetch(url, {
  method: method,
  headers: {
  //  ^^^
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: postData.title,
    content: postData.content,
  }),
})

Because the Content-Type header isn't being sent due to the misspelling, body-parser or express.json() (whichever you're using) doesn't parse the request body.由于拼写错误导致Content-Type header 未发送,因此body-parserexpress.json() (无论您使用的是哪个)都不会解析请求正文。

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

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