I've enabled CORS in the console for a Lambda function following these instructions.
The API is also an express server that enables CORS for all methods:
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
});
However the browser is still blocking the request because it is not receiving the Access-Control-Allow-Origin
header. This is the complete message:
home:1 Access to XMLHttpRequest at 'https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco/myendpoint' from origin 'http://localhost:4200' 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.
How do we trouble shoot this?
The testing approach in the instructions provide a curl command like this:
curl -v -X OPTIONS -H "Access-Control-Request-Method: POST" -H "Origin: http://localhost:4200" https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco
However this fails due to a missing authentication token:
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 403
< content-type: application/json
< content-length: 42
< date: Wed, 19 Feb 2020 01:45:47 GMT
< x-amzn-requestid: a529894d-19ff-4c95-915b-45c4098d30ea
< x-amzn-errortype: MissingAuthenticationTokenException
< x-amz-apigw-id: IHvz3Fp_IAMF43g=
< x-cache: Error from cloudfront
< via: 1.1 58e86c1faaee1b15c90e95d794e240dd.cloudfront.net (CloudFront)
< x-amz-cf-pop: ORD51-C3
< x-amz-cf-id: jyTAo6OUrhUWWVNOSdk6M0384K515YzE0V9Vgg-WhfXXkLDzLofr9Q==
<
* Connection #0 to host szxjza7hz5.execute-api.us-east-1.amazonaws.com left intact
{"message":"Missing Authentication Token"}
Try adding these fields to response header:
const response = {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials" : true,
},
body: "...",
statusCode: 200
}
You could also experience the same error if not redeploy the API after updating it. Try to redeploy it as below: