Configure CORS response headers on AWS Lambda?

蓝咒 提交于 2019-12-29 01:32:43

问题


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?


回答1:


If you're using {proxy+} endpoint, you must handle CORS HTTP requests in the Lambda function. The implementation depends on the framework you're using. For Express, the easiest solution is to simply use Express CORS middleware.

If you don't want to handle CORS requests by Lambda, try changing the settings of your Lambda Method to handle CORS on the API Gateway level.

Here's a detailed official tutorial for CORS setup on AWS API Gateway.

It's also critical that you allow header X-Api-Key in Access-Control-Allow-Headers otherwise auth won't work and you'll get errors.

EDIT: In November 2015 the API Gateway team added a new feature to simplify CORS setup.




回答2:


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




回答3:


If you're using JQuery $.ajax, it will send the X-Requested-With with the POST following the OPTIONS request, so you need to make sure when setting up your OPTIONS access-control-accept-headers on AWS API to include that header: X-Requested-With along with the others.



来源:https://stackoverflow.com/questions/31911898/configure-cors-response-headers-on-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!