简体   繁体   English

带有JSON的bodyParser发行

[英]Issue w/ JSON for bodyParser

I'm sending data in my React component via the Fetch API, and returning the result as JSON. 我正在通过Fetch API在我的React组件中发送数据,并将结果作为JSON返回。 When POSTED on my Express server, I use the jsonParser method from bodyParser to parse through the data, but insead I'm only getting back a empty object. 在Express服务器上发布时,我使用bodyParser中的jsonParser方法来解析数据,但实际上,我只得到了一个空对象。 I do not understand what's the issue with jsonParser, because if I use textParser, my data get sent fine. 我不明白jsonParser的问题是什么,因为如果我使用textParser,我的数据会很好地发送。

Edit: When printing out the request (req) on the server, it is showing that nothing was received in the body. 编辑:在服务器上打印出请求(req)时,表明正文中什么都没有收到。 This only happens with jsonParser though, and not textParser. 不过,这仅发生在jsonParser上,而不发生在textParser上。

Fetch: 取:

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

Express: 表达:

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

Assuming you want to post the {name: 'Justin'} object, you'll want something like 假设您要发布{name: 'Justin'}对象,则需要类似

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

The body parameter does not accept an array (which is what you were passing). body参数不接受数组(您正在传递的数组)。


If you did mean to post an array, simply change the body value to 如果您确实要发布数组,只需将body值更改为

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

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

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