【发布时间】:2018-08-20 19:01:51
【问题描述】:
我没有从服务器端的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 属性,但没有成功。
【问题讨论】:
-
你在 node.js 中使用过
body-parser吗?
标签: node.js reactjs express fetch