CORS error when calling function in browser
See original GitHub issueHi all,
I have been digging for many hours on the internet, reading all the issue comments and try the solution at : https://github.com/serverless/serverless/issues/1955 However, when I try to call the serverless function in browser I still get the below error (the serverless function can be invokes correctly through serverless invoke cli)
Fetch API cannot load (...Lambda url ). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. The response had HTTP status code 502. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am using fetch API in frontend with the following headers :
let myHeader = new Headers();
myHeader.append('Accept', 'application/json');
myHeader.append('Content-Type', 'application/json');
even if I add
myHeader.append('Access-Control-Allow-Origin', '*');
it shows another error:
Fetch API cannot load (...Lambda url ). Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
my serverless.yml has the following config:
events:
- http:
path: cloudvision
method: post
cors: true
my hander callback response:
callback(null, {
statusCode : 200,
headers: {
"Access-Control-Allow-Origin" : "*"
},
body : JSON.stringify(textResult)
});
also, I used postman to test it, it returns body:
{
"message": "Internal server error"
}
headers:
content-length →36
content-type →application/json
date →Fri, 04 Aug 2017 12:22:12 GMT
status →500
via →1.1 2f1de9e70f3d7a82dd76483049fb670e.cloudfront.net (CloudFront)
x-amz-cf-id →nkCCBFOKNaE35vxbBduJYbd18tlKAntEt9BQkTieGvPf0o5OyCZvEQ==
x-amzn-requestid →8afbfd57-790f-11e7-aa0f-4f1e557725a5
x-cache →Error from cloudfront
Is this related to aws apiGateway issues or serverless config issues?
Thanks
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:7 (3 by maintainers)
@choychris Addings
cors: true
in yourserverless.yml
isn’t enough to make CORS work. You also need to add the CORS headers to the response from your Lambda. It looks like you’re trying to add at them in the request. If you’re using Lambda Proxy integration (the default) then it will mean adding something like this to your response:Finally, if your Lambda fails for some reason (timeout, error, etc) then the response is the one generated by the API Gateway which will also lack the CORS headers.
Super nice! Glad to hear that this fixes your problem @choychris!
Thanks for helping out @buggy, @RafalWilinski and @horike37 🙏 💯