I have an API Gateway built on AWS, with various resources & methods already properly reaching to Lambda endpoints.
As I try to make a POST
request on React to the API, everything works smooth. However, GET
request provides CORS Error: HeaderDisallowedByPreflightResponse
when I call the function.
Final details to add:
- I tested my code on NodeJS and surprisingly the error is not generated, fetch works smooth.
- I made sure to enable CORS at Amazon API Gateway. Deployed it properly, as it works at NodeJS
- I added "Access-Control-Allow-Headers": "Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization" together with other details suggested (Origin,Methods) NodeJS works smooth, React still generates same error.
What am I doing wrong? Is this a general CORS limitation, React issue, Browser issue, or something to do with my code?
My source code on React (this one generates the error):
async function getUserGroups() {
try {
const response = await fetch(APIroot + "/user" + "?userID=mymail@gmail.com", {
method: 'GET',
headers: {
"accept": 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, PUT, PATCH, GET, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization"
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log(result);
return result;
} catch (err) {
console.log(err);
}
}
My source code on NodeJS (this one fetches the data):
async function getUser() {
try {
const response = await fetch(APIroot + "/user" + "?userID=mymail@gmail.com", {
method: 'GET',
headers: {
"accept": 'application/json',
"Access-Control-Allow-Origin": APIroot + "/user",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization"
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log(result);
return result;
} catch (err) {
console.log(err);
}
}