首页 > 解决方案 > 无法将数据从 HTTP 发布请求传递到 javascript(expressjs) 控制器

问题描述

我在前端使用 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()
    }
  });

标签: javascriptnode.jsreactjsexpress

解决方案


属性header应该是。headers

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

因为Content-Type由于拼写错误而没有发送标头,body-parser或者express.json()(无论您使用的是哪个)不解析请求正文。


推荐阅读