Search code examples
amazon-web-servicesaws-lambdaaws-api-gateway

How to add CORS header to AWS API Gateway response with lambda proxy integration activate


I use lambda as backend for AWS API Gateway with lambda proxy integration and want to add CORS into response header.

According to documentation:

http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

However, you must rely on the back end to return the Access-Control-Allow-Origin headers because the integration response is disabled for the proxy integration.

How can I program it in my lambda function with Python.


Solution

  • you need to add a method "options" to your api gateway and using a proxy lambda... return

    result.headers = { "Access-Control-Allow-Origin": "domain.com" }
    

    so when the browser will first call options to your server it will return the CORS headers.

    the thing is that, by default your lambda method will be called for "any" method, so you need to change the default one to get,post or whatever you need

    note: you could also use the same method, like any or options,get,post and if it is a options call, only return status 200 and the cors header. it depends if you are using or not an auth method for get,post,etc

    there is an option in Lambda console "Enable CORS" if you are just using lambda with nothing strange