繁体   English   中英

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

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

我在前端使用 react,在后端使用 expressjs。 创建一个简单的 post 请求并通过前端将 json 数据传递到后端。 请求由 body{title:"some title", content:"some content"} 组成。 在后端,如果我 console.log(req.body),我得到一个空的 object。 此外,如果我使用 postman 它可以正常工作。 前端代码:

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

后端代码:

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()
    }
  });

header属性应该是headers

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

由于拼写错误导致Content-Type header 未发送,因此body-parserexpress.json() (无论您使用的是哪个)都不会解析请求正文。

暂无
暂无

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

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