AWS API Gateway的CORS问题

时间:2018-04-14 12:58:11

标签: cors aws-api-gateway

我从我的网页发送post请求到AWS API Gateway,它正在调用lambda函数。在API网关中启用CORS。

错误:

  

无法加载api_gatewau_url:没有'Access-Control-Allow-Origin'   标头出现在请求的资源上。起源   因此,'url'不允许访问。

资源有两种方法:

  1. 选项(集成MOCK)
  2. POST(整合Lambda)
  3. 如何解决CORS问题?

    以下是发送帖子请求的代码。

    GetDIBits(hSectionDC, hBmpSection, 0, bmpSmallInfo.bmiHeader.biHeight, dataBuffer3, &bmpSmallInfo, DIB_RGB_COLORS);
    

    我还试图添加带有allow origin true的标题,但没有运气。
    最奇怪的是,相同的配置和请求我尝试使用不同的api网关然后它正常工作没有任何错误。

2 个答案:

答案 0 :(得分:2)

如果您在API Gateway中使用代理集成,则无法从API Gateway启用CORS。您必须从Lambda代码本身设置标头“ Access-Control-Allow-Origin”。

它在doc中提到。

Python代码示例:

    response = {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps({'message': 'CORS enabled')
    }
    return response

答案 1 :(得分:1)

根据您的集成类型,您需要返回COR的标题。

更多细节可以在

找到

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#The_HTTP_response_headers

如果您使用的是任何集成,则可以从Lambda或要集成的其他来源返回标题。

对于Lambda,

module.exports.hello = function(event, context, callback) {

    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "https://domain:port", // 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);
};

如果您使用的是S3,

https://docs.aws.amazon.com/AmazonS3/latest/user-guide/add-cors-configuration.html

API网关CORS映射:

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

希望它有所帮助。

相关问题