I'm trying to send an API GET request with the Authorizer header. The request works fine with curl and Postman: Postman response
If I send the GET request without the Authorizer header it works as expected but as soon as I add the header it sends the preflight OPTIONS and it fails.
This is my code:
function GetData() {
var req = new XMLHttpRequest();
req.addEventListener("load", () => {
console.log(req.responseText);
});
req.open(
"GET",
"https://qrdc992lul.execute-api.eu-west-1.amazonaws.com/dev/account"
);
req.setRequestHeader("Authorization", "Bearer " + token);
req.withCredentials = true;
req.send();
}
I get the following response:
Failed to load resource: the server responded with a status of 403 ()
Access to XMLHttpRequest at 'https://qrdc992lul.execute-api.eu-west-1.amazonaws.com/dev/account' from origin 'https://ogx7o.csb.app' 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.
Response header:
content-length: 42 content-type: application/json date: Tue, 04 Feb 2020 13:09:37 GMT status: 403 via: 1.1 37adc88abfddc6deef6672a655706cd4.cloudfront.net (CloudFront) x-amz-apigw-id: HX36rHhxDoEFXxw= x-amz-cf-id: hgFvoQwvQ96Uge3ciwwvd41RCNyX1oZyVydPIyXqPQxe0aAeklM2WA== x-amz-cf-pop: MAN50-C3 x-amzn-errortype: MissingAuthenticationTokenException x-amzn-requestid: 4383a667-e30b-44fb-ac3b-bd532e99f1d4 x-cache: Error from cloudfront
I had a read about CORS headers and preflight and I kinda figured that the issue is that there's no Access-Control-Allow-Origin in the response header but don't know how to resolve the issue.
I have added the code snippet to Codesandbox: https://codesandbox.io/s/fragrant-river-ogx7o
API is API Gateway Lambda Proxy integration.
I'm still learning React and I have the feeling I'm sending the request wrong. What am I missing?