Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure CORS response headers on AWS Lambda?

I'm trying to create a new service using AWS API Gateway, but I found out the browser automatically calls OPTIONS method in order to obtain CORS information.

The problem is that AWS API Gateway does not offer a native way to configure CORS headers.

Is it possible to create a Lambda Script in order to respond to OPTIONS method?

like image 821
Alessandro Oliveira Avatar asked Aug 10 '15 05:08

Alessandro Oliveira


People also ask

How do you pass headers in Lambda?

To pass custom headers from an API Gateway API to a Lambda function, use a body mapping template. The API sends the updated API request to a Lambda function to process the headers. Then, the Lambda function returns one or more header values from the original API request.

How do I enable CORS on AWS?

Enable CORS support on a REST API resourceSign in to the API Gateway console at https://console.aws.amazon.com/apigateway . Choose the API from the APIs list. Choose a resource under Resources. This will enable CORS for all the methods on the resource.


1 Answers

If you have lambda-proxy enabled, you need to set the CORS headers manually:

module.exports.hello = function(event, context, callback) {      const response = {       statusCode: 200,       headers: {         "Access-Control-Allow-Origin" : "*", // Required for CORS support to work         "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS       },       body: JSON.stringify({ "message": "Hello World!" })     };      callback(null, response); }; 

https://serverless.com/framework/docs/providers/aws/events/apigateway#enabling-cors

like image 85
sqren Avatar answered Sep 27 '22 21:09

sqren