bodyParser 问题 w/ JSON

Issue w/ JSON for bodyParser

我正在通过 Fetch API 在我的 React 组件中发送数据,并将结果返回为 JSON。在我的 Express 服务器上发布时,我使用 bodyParser 中的 jsonParser 方法来解析数据,但我只得到一个空对象。我不明白 jsonParser 有什么问题,因为如果我使用 textParser,我的数据就可以正常发送。

编辑:在服务器上打印请求 (req) 时,显示正文中没有收到任何内容。这只发生在 jsonParser 上,而不是 textParser。

获取:

fetch('./test',{
  method: 'POST',
  body: ["{'name':'Justin'}"]
})
.then((result) => {
      return result.json();
    })
.then((response) => {
      console.log(response);
    })
.catch(function(error){
      //window.location = "./logout";
     console.log(error);
    });

快递:

app.use('/test', jsonParser, (req,res) =>{
   res.json(req.body);
})

假设您想要 post {name: 'Justin'} 对象,您将需要

fetch('test', {
  method: 'POST',
  body: JSON.stringify({name: 'Justin'}),
  headers: new Headers({
    'Content-Type': 'application/json; charset=utf-8'
  })
})

body 参数不接受数组(您传递的是数组)。


如果您的意思是 post 数组,只需将 body 值更改为

JSON.stringify([{name: 'Justin'}])