javascript - 无法将数据从 HTTP 发布请求传递到 javascript(expressjs) 控制器
问题描述
我在前端使用 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()
}
});
解决方案
属性header
应该是。headers
fetch(url, {
method: method,
headers: {
// ^^^
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: postData.title,
content: postData.content,
}),
})
因为Content-Type
由于拼写错误而没有发送标头,body-parser
或者express.json()
(无论您使用的是哪个)不解析请求正文。
推荐阅读
- pyspark - 从 pyspark 数据框列中删除 HTML 标记
- angular - 由于多重错误,将 Angular 应用程序推送到 Heroku 时遇到问题
- c - 使用 write() 写入文件时文件被覆盖
- python - 如何阅读 django-rest-framework 或任何其他 python 库的源代码
- javascript - 用户注销时是否需要在前端手动清除所有cookie
- c# - 我们可以向 EWS 推送通知回调添加自定义标头吗
- python - 预测罕见事件分类,有没有比使用 LSTM Keras 更“简单”的方法?
- python - 为什么 tf.read_file() 和 tf.decode_raw() 会改变大小?
- react-native - 如何在这个 React 导航设置中使用 contentComponent
- php - 使用 eloquent laravel 优化查询