我正在通过fetch api在我的反应组件中发送数据,并将结果返回为JSON。当在我的Express服务器上发布时,我使用从BodyParser的JSONPARSER方法通过数据解析,但是INSEAD我只会回到一个空对象。我不明白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);
});
express:
app.use('/test', jsonParser, (req,res) =>{
res.json(req.body);
})
假设您要发布{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'}])