Node.js 快递邮寄方式可以';t读取属性';toString';
我有一个带有以下Post呼叫的express服务器:Node.js 快递邮寄方式可以';t读取属性';toString';,node.js,reactjs,express,Node.js,Reactjs,Express,我有一个带有以下Post呼叫的express服务器: 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(
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”。当我在后端express服务器上记录请求时,如下所示:
{ '{"guitarMake":"Fender","guitarModel":"Jazzmaster","guitarSerial":"000000001","guitarColour":"Placid Blue","guitarOwnerId":"dummyuser","guitarYear":"2019"}': '' }
我不明白为什么我的请求是这样的。只有当它通过react应用程序发送时。在postman上,服务器端看起来很正常。我做错了什么 您似乎将主体作为字符串而不是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);
});
您似乎将主体作为字符串而不是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);
});