【发布时间】:2020-09-16 02:38:47
【问题描述】:
我在前端使用 react,在后端使用 expressjs。创建一个简单的 post 请求并通过前端将 json 数据传递到后端。请求由 body{title:"some title", content:"some content"} 组成。在后端,如果我 console.log(req.body),我得到一个空对象。另外,如果我使用邮递员,它可以正常工作。 前端代码:
fetch(url, {
method: method,
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: postData.title,
content: postData.content
})
})
后端代码:
const title = req.body.title;
const content = req.body.content;
console.log(req);
res.status(201).json({
message: 'created nicely',
post: {
_id: '78',
title: title,
content: content,
creator: { name: 'mera naam' },
createdAt: new Date()
}
});
【问题讨论】:
-
method在“方法:方法”中有值吗?浏览器控制台或网络工具有任何错误吗?你启用 cors 了吗?
标签: javascript node.js reactjs express