在react中利用fetch进行CORS跨域需要注意的点
当我们直接在fetch的url中输入完整的http时,就算加了"Access-Control-Allow-Origin": "*"
也会报下面的错误:
Access to fetch at ‘http://xxx.xx.xxx.xx:8080/admin/onLogin’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
POST http://xxx.xx.xxx.xx:8080/admin/onLogin net::ERR_FAILED
TypeError: Failed to fetch
为了解决这个错误,实现跨域,我们需要在package.json文件下加proxy,这样就不会报错并且实现跨域了。
"proxy": "http://xxx.xx.xxx.xx:8080"
之后实现的上传json数据和上传formData就很简单了
上传json数据
fetch("/admin/onLogin", {
method: "POST",
headers: new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json;charset=UTF-8",
}),
body: JSON.stringify({
username: this.state.userName,
password: this.state.password,
}),
})
.then((res) => {
return res.json().then((response) => {
console.log(response);
});
})
.catch((error) => {
console.error(error);
});
上传formData
var content = document.getElementById("content").innerHTML;
var formData = new FormData();
formData.append("type", this.state.value);
formData.append("title", this.state.title);
formData.append("content", content);
for (var i = 0; i < this.state.fileList.length; i++) {
formData.append("image", this.state.fileList[i].originFileObj);
}
fetch("/notice/send", {
method: "POST",
headers: new Headers({
"Access-Control-Allow-Origin": "*",
"User-Token": this.state.token,
}),
contentType: false,
processData: false,
body: formData,
dataType: "text",
})
.then((res) => {
return res.json().then((response) => {
console.log(response);
});
})
.catch((error) => {
console.error(error);
});