无法将数据从HTTP post请求传递到javascript(expressjs)控制器
我在前端使用react,在后端使用expressjs。创建一个简单的post请求,并通过前端将json数据传递到后端。请求由正文{标题:“某些标题”,内容:“某些内容”}组成。在后端,如果我使用console.log(req.body),我将得到一个空对象。如果我使用邮递员,它也能正常工作。 前端代码:无法将数据从HTTP post请求传递到javascript(expressjs)控制器,javascript,node.js,reactjs,express,Javascript,Node.js,Reactjs,Express,我在前端使用react,在后端使用expressjs。创建一个简单的post请求,并通过前端将json数据传递到后端。请求由正文{标题:“某些标题”,内容:“某些内容”}组成。在后端,如果我使用console.log(req.body),我将得到一个空对象。如果我使用邮递员,它也能正常工作。 前端代码: fetch(url, { method: method, header: { 'Content-Type': 'application/json'
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()
}
});
标题
属性应为
因为由于拼写错误,
内容类型
头没有被发送,正文解析器
或express.json()
(无论您使用哪个)都不会解析请求正文。方法
在“方法:方法”中有值?浏览器控制台或网络工具中有错误吗?您启用了cors吗?
fetch(url, {
method: method,
headers: {
// ^^^
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: postData.title,
content: postData.content,
}),
})