I am using serverless for creating and deploying my lambda functions. I am using Node.js - HTTP API
template from serverless. I have created few lambda functions and deployed them using command sls deploy
.
The functions were deployed successfully and I am able to query lambda function response using postman.
But, when I want to invoke same lambda function through my React webapp (using axios) it is throwing me A CORS Error
if I included any headers.
For ex. I want to send Authorization
token in header or Content-type
as json
in header. Any of this doesn’t worked.
After this, I have added following headers in my lambda function response
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
After this, in AWS API Gateway console, I have configured CORS with wildcard origin and allowed All HTTP methods. After deploying this setup It’s still doesn’t worked.
I have also tried tweaking my serverless.yml
file but my bad it didn’t worked either
3
Answers
If you want default setting, adding the following snippet should do the trick:
For more detailed
cors
settings (and also for reference what the shortcut above will do), please refer to: https://www.serverless.com/framework/docs/providers/aws/events/http-api#cors-setupI also stumbled across this issue when I was working with serverless. I initiated the project using
serverless
and then selected the template asNode.js - HTTP API
.Everything is working as expected in postman but not in my FE which is built using Angular 10.
But, then I came across the
Node.js - Express template
provided by serverless.It contains bare minimum
Express.js
code, with availability of configuring CORS as dependency just like classicalNode.js
server.I have tried it and it worked like a charm !!!
But, Before using it keep in mind
Node.js
server as a single lambda function.The settings that you have provided is not compliant with CORS specifications. In order to allow your client to send credentials,
Access-Control-Allow-Credentials
header has to be set totrue
. You have done this step correctly. But if you are setting it totrue
, yourAccess-Control-Allow-Origin
can’t be wildcard*
. It has to be the specific domain.One way to solve your issue is to:
OPTIONS
method of your API gateway route. This lambda should return a header (only if request comes from your own domain. check it in your lambda logic)Refer to this SO for steps involved
You can refer to this SO post to implement the header setting and caveats on doing it this way.
Why
OPTIONS
is needed? – Depending upon the API call, browser will trigger a preflight request before making the actual API call. This comes as anOPTIONS
request to your API gateway and it should return correct headers for your browser to make the actual call. For understanding this process better refer to this MDN article