【问题标题】:Issue w/ JSON for bodyParser带有 JSON 的 bodyParser 问题
【发布时间】:2017-10-01 23:10:30
【问题描述】:

我通过 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);
})

【问题讨论】:

    标签: javascript json express fetch-api body-parser


    【解决方案1】:

    假设你想发布 {name: 'Justin'} 对象,你会想要类似的东西

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

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


    如果您确实打算发布一个数组,只需将 body 值更改为

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 2014-07-26
      • 2017-03-14
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多