【问题标题】:Not able to pass data from HTTP post request to the javascript(expressjs) controller无法将数据从 HTTP 发布请求传递到 javascript(expressjs) 控制器
【发布时间】:2020-09-16 02:38:47
【问题描述】:

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

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

【问题讨论】:

  • method 在“方法:方法”中有值吗?浏览器控制台或网络工具有任何错误吗?你启用 cors 了吗?

标签: javascript node.js reactjs express


【解决方案1】:

header 属性应为 headers

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

由于拼写错误,Content-Type 标头未发送,body-parserexpress.json()(无论您使用哪个)不会解析请求正文。

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 2020-02-01
    • 2015-07-22
    • 2019-12-19
    • 2015-11-06
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多