【发布时间】:2021-12-25 18:14:18
【问题描述】:
我正在尝试使用 React/axios 从 AWS 端点获取数据,但是当我尝试发出请求时,我收到了这个 CORS 错误:
从源“http://localhost:3000”访问“https://myAWS.com/login”处的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头请求的资源。
当我尝试构建托管的 github 页面时,我也遇到了同样的错误。但是当我在另一个托管网站上使用 Vanilla js 时它可以工作,我在 axios 上发送的请求是否错误?
香草
let body = {
"name": "Bbbb 202",
"email": "bbbb2220@bob.com",
"password": "122",
"wallet": "bbbbB202222"
};
var http = new XMLHttpRequest();
var url = 'https://myAWS.com/login';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(body);
反应
async SendRequest(method, url, callback, body){
axios.request({
method: 'POST',
data: JSON.stringify(body),
headers: {
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Bearer " + localStorage.getItem("token"),
},
url: url
})
.then(response => {
console.log(response);
callback({
status: response.status,
data: response.data,
});
})
.catch(err => {
console.log(err);
callback({
status: err.status,
data: err,
});
});
}
【问题讨论】:
-
这是因为您需要在标题中启用 CORS。添加:
'Access-Control-Allow-Origin': '*',或same-origin到您后端的标题中。注意:这会在您的服务器中打开一个安全漏洞,因此请在使用之前对其进行充分研究。 -
但是如果是后端的问题,香草版本也不能正常工作吗?
标签: javascript reactjs http axios cors