Search code examples
node.jsamazon-web-servicesaws-lambdaaws-api-gatewayserverless-framework

Not able to access lambda function when invoked with headers


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


Solution

  • I also stumbled across this issue when I was working with serverless. I initiated the project using serverless and then selected the template as Node.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 classical Node.js server.

    I have tried it and it worked like a charm !!!


    But, Before using it keep in mind

    • It will deploy a whole Node.js server as a single lambda function.
    • Means, all the API's will be inside a single lambda and not as one lambda one API
    • It will enable manual configuration of CORS