我正在开发具有以下表格的应用程序:客户|运输。 Client_Id是传输的外键。我必须为传输创建一个创建向导,在第一步中,我可能需要创建一个客户端,并在下一步中通过React状态传递client_id。我要实现的是发布服务器以创建客户端,并在同一请求中检索生成的client_id。
那是我的后端代码:
exports.createClient = function(req,res,next){
const text = 'INSERT INTO public.client (name, "isCompany", mobile, phone, email, tax_code, addr) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id'
const values = [req.body.name,req.body.isCompany,req.body.mobile,req.body.phone,req.body.email,req.body.tax_code,req.body.addr];
DBclient.query(text,values,function(err,result){
if (err){
console.log(err)
res.status(400).send(err);
}
res.sendStatus(200).send(result.rows[0].id);
});
};
在这里,我尝试检索响应:
var formData = new FormData();
formData.append('name', this.state.client_name);
formData.append('isCompany', this.state.client_isCompany);
formData.append('tax_code', this.state.client_tax_code);
formData.append('addr', this.state.client_addr);
formData.append('phone', this.state.client_phone);
formData.append('mobile', this.state.client_mobile);
formData.append('email', this.state.client_email);
await fetch(clienturl, {
method: 'POST',
body: formData
}).then(data => this.setState({client_id:data}));
以下是我的状态:console log output for state
如果有人可以帮助您,我将不胜感激。
[经过几次尝试使用postman和console.log()调试后,我意识到问题出在服务器端,而我没有设置响应的主体。在邮递员上,我看到服务器仅以状态码(200 OK)响应。使这项工作起作用的更新是:
DBclient.query(text,values,function(err,result){
if (err){
console.log(err)
res.status(400).send(err);
}
res.status(200).send({client_id : result.rows[0].id});
});