我通过Fetch API在React组件中发送数据,并以JSON的形式返回结果。在我的Express服务器上发布时,我使用来自bodyParser的bodyParser方法解析数据,但是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);
});
特快:
app.use('/test', jsonParser, (req,res) =>{
res.json(req.body);
})
发布于 2017-05-03 17:11:32
假设您想发布{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'}])
https://stackoverflow.com/questions/43771573
复制相似问题