I am trying to get data from a AWS endpoint using React/axios, but when I try to make a request I get this CORS error:
Access to XMLHttpRequest at 'https://myAWS.com/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
when I try on my hosted github pages build, I also get the same error. But when I use Vanilla js on another hosted website it works, am I sendig my requests wrong on axios?
VANILLA
let body = {
"name": "Bbbb 202",
"email": "[email protected]",
"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);
REACT
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,
});
});
}
CodePudding user response:
These are not the same request. The 'vanilla' request looks like it might qualify for what's known as a 'safe request'. To qualify as a safe request, content-type must be application/x-www-form-urlencoded
(or 2 others), and not use any restricted HTTP methods.
I wrote more extensively about it here as well: https://evertpot.com/no-cors/