我有一个快递服务器,带有以下邮政电话:
app.post('/api/guitars/' , function(req, res){
const body = req.body;
//var inputGuitar = new Guitar(body.guitarMake.toString(), body.guitarModel.toString(), body.guitarSerial.toString(), body.guitarColour.toString(), body.guitarOwnerId.toString(), body.guitarYear.toString());
db.query(`INSERT INTO Guitar (GuitarMake, GuitarModel, GuitarSerial, GuitarColour, GuitarOwnerId, GuitarYear) VALUES (?, ?, ?, ?, ?, ?)`,
[body.guitarMake.toString(), body.inputGuitar.guitarModel.toString(), body.guitarSerial.toString(), body.guitarColour.toString(), body.guitarOwnerId.toString(), body.guitarYear.toString()], function(err, res){
if (err) {
console.log(err);
} else {
res.status(200).json(res);
}
});
res.end();
});
我的前端代码(这是一个React.js应用程序)正在控制台记录此JSON对象:
{"guitarMake":"Fender",
"guitarModel":"Jazzmaster",
"guitarSerial":"000000001",
"guitarColour":"Placid Blue",
"guitarOwnerId":"dummyuser",
"guitarYear":"2019"}
在此块生成的内容:
if (isValid) {
var guitar = {
"guitarMake" : this.state.GuitarMake,
"guitarModel" : this.state.GuitarModel,
"guitarSerial" : this.state.GuitarSerial,
"guitarColour" : this.state.GuitarColour,
"guitarOwnerId" : this.state.GuitarOwnerId,
"guitarYear" : this.state.GuitarYear
}
var json = JSON.stringify(guitar);
console.log(json);
// do something..
fetch("APIGATEWAY", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: json,
}).then(res => {
console.log(res);
});
每次我将请求发送到服务器时,我都会收到一条错误消息:TypeError:无法读取未定义的属性'toString'。当我在后端快递服务器上控制台记录请求时,它看起来像这样:
{ '{"guitarMake":"Fender","guitarModel":"Jazzmaster","guitarSerial":"000000001","guitarColour":"Placid Blue","guitarOwnerId":"dummyuser","guitarYear":"2019"}': '' }
我不知道为什么我的请求看起来像这样。只有当它通过react应用程序发送时。在邮递员上,它在服务器端看起来很正常。我究竟做错了什么?
答案 0 :(得分:0)
您似乎将正文作为字符串而不是json。
首先,确保已将json中间件添加到服务器对象:
app.use(express.json());
第二,您使用了错误的mime类型。如果打算让服务器解析json对象,则应使用application/json
:
fetch("APIGATEWAY", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json', // Here!
},
body: json,
}).then(res => {
console.log(res);
});