【发布时间】:2018-12-28 01:48:07
【问题描述】:
我想更新我在后端使用 Node.js、在前端使用 React 和 MySQL 开发的表的行的数据关于数据库。
我的编辑类:
constructor(props) {
super(props)
this.state = {
clients: [],
Prenom: '',
Nom: '',
FAX: '',
Telephone: '',
Email: '',
Adresse1: '',
Adresse2: '',
Code: props.match.params.Code
}
// this.logChange = this.logChange.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
handleEdit(event) {
//Edit functionality
//event.preventDefault()
var client = {
Prenom: this.state.Prenom,
Nom: this.state.Nom,
FAX: this.state.FAX,
Telephone: this.state.Telephone,
Email: this.state.Email,
Adresse1: this.state.Adresse1,
Adresse2: this.state.Adresse2
}
axios({
method: 'put',
url: "http://localhost:4000/app/editclient/" + this.props.match.params.Code,
data: client,
withCredentials: true,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"Accept": "application/json",
}
}).then(function(response) { // empty form
this.setState({
Code: ""
});
this.setState({
Prenom: ""
});
this.setState({
Nom: ""
});
this.setState({
FAX: ""
});
this.setState({
Telephone: ""
});
this.setState({
Email: ""
});
this.setState({
Adresse1: ""
});
this.setState({
Adresse2: ""
});
}.bind(this)).catch(function(error) {
console.log(error);
});
event.preventDefault();
}
<Button type="submit" color="success" onClick={(event) => this. handleEdit(event)} >Modifier</Button>
我的路由器:
exports.editclient = function(req, res) {
var data = {
Prenom: req.body.Prenom,
Nom: req.body.Nom,
FAX: req.body.FAX,
Telephone: req.body.Telephone,
Email: req.body.Email,
Adresse1: req.body.Adresse1,
Adresse2: req.body.Adresse2,
};
var Code = req.params.Code
console.log(req.params);
// var Code = data.Code
connection.query("UPDATE clients set ? WHERE Code = ? ", [data, req.params.Code], function(error, results, fields) {
if (error) throw error;
else {
res.send(JSON.stringify(results));
console.log("Data is updated");
}
});
};
我的服务器:
router.put('/editclient/:Code', clients.editclient);
我使用 URL http://localhost:4000/app/editclient/2222 使用 Postman 运行后端,它运行良好,但是当我运行前端时,数据没有更新,我得到:
我该如何解决?
【问题讨论】:
-
尝试删除 "Access-Control-Allow-Origin": "*" ,因为服务器应该指定此访问权限而不是客户端...
-
@mikkelrd 端口 3000 受 ReactJS 影响,4000 受 NodeJs 影响。
-
@KpTheConstructor 我删除了它,但我得到了同样的错误。
-
我解决了,在我的路线上添加
:Code{ path: '/clients/editclient/:Code', name: 'EditClient', component: EditClient }
标签: javascript reactjs http axios put