gpt4 book ai didi

javascript - PUT 请求在 Axios 上不起作用

转载 作者:行者123 更新时间:2023-12-01 01:51:44 29 4
gpt4 key购买 nike

我想更新我的表的行数据,后端使用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 运行后端,它运行良好,但是当我运行前端时,数据没有更新,我得到:

enter image description here

我该如何解决这个问题?

最佳答案

您尝试访问的 localhost:4000 服务器未启用跨域资源共享 (CORS)。这就是它不起作用的原因。

另一方面,它可以与 Postman 一起使用,因为 Postman 它是一个开发工具,而不是浏览器。因此,它不会受到未启用 CORS 的影响。

这是easiest way to enable CORS support to your server, if you use Express for NodeJS .

Use the node.js package cors. The simplest usage is:

var cors = require('cors')

var app = express()
app.use(cors())

关于javascript - PUT 请求在 Axios 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51430839/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com