node.js - React - 获取请求未在正文中发送内容
问题描述
我没有从fetch
服务器端的请求中获取正文对象中的数据。我已经在 SO 上尝试过其他解决方案,但到目前为止,我的情况没有任何效果。我在后端使用 Node express,在前端使用 React。
在组件中:
addCity = _ => {
const { city } = this.state;
fetch('http://localhost:3003/city_create', {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
create_name: city.name,
create_district: city.district,
create_population: city.population
})
})
.then(res => {
console.log(res);
this.getCities;
})
.catch(err => console.log(err))
}
服务器路由:
router.post('/city_create', (req, res) => {
console.log("Trying to create new city...")
const { create_name, create_district, create_population } = req.body;
//debugger
const queryString = "INSERT INTO city (Name, District, Population, CountryCode) VALUES (?,?,?,'PAK')";
getConnection().query(queryString, [create_name, create_district, create_population], (err, rows, fields) => {
console.log(create_name, create_district, create_population);
if (err) {
console.log('A db error occurred:' + err);
res.sendStatus(500);
return;
//throw err;
}
console.log("Inserted a new City with Id: ", rows.insertId);
});
res.end();
});
也尝试在标题中使用FormData
和属性,但没有运气。accept
解决方案
您需要安装body-parser
模块以提取传入请求流的整个正文部分并将其公开在 req.body 上。
之前是express的一部分,现在需要单独安装。
npm install body-parser --save
并将中间件用作:
app.use(bodyParser.json())
推荐阅读
- reactjs - 使用 github pages 部署时 React App Blank 的第一页
- multidimensional-array - 在fortran中通过hdf5写入一大块MPI分布式数据
- swift - 使用过滤器使用 MVVM 在 SwiftUI 中重新加载数据
- python - 我删除了日期字段,但我仍然在 django 中收到 datetime_re.match(value) TypeError
- google-sheets - Duplicating/triplicating rows of data
- linux - 从 AWS Lambda 在 EC2 Linux 实例中运行脚本
- opengl - 不按位将 2 个整数编码为 RGBA
- python - 列表在python中没有正确连接
- sql - 查询列值小于当前行值的行数
- python - 聚类:如果因素不独立,会有问题吗?如何评价模型?