【问题标题】:aws api gateway - No 'Access-Control-Allow-Origin' header is present on the requested resource if using cloudformationaws api gateway - 如果使用 cloudformation,请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2020-11-08 20:18:52
【问题描述】:

我在前端应用程序中调用 GET 请求时遇到以下错误
我尝试将 Access-Control-Allow-Origin: * 添加到我的模板中,但它不起作用。

Access to XMLHttpRequest at 'https://xxxxxx.execute-api.ap-southeast-1.amazonaws.com/dev/banner' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我用于 GET 请求的 lambda 函数(已根据评论更新但仍然无法正常工作)

'use strict'
const AWS = require('aws-sdk');

exports.handler = async function (event, context, callback) {
    const documentClient = new AWS.DynamoDB.DocumentClient();

    let responseBody = "";
    let statusCode = 0;

    const params = {
        TableName : "myTable",
    };

    try{
        const data = await documentClient.scan(params).promise();
        responseBody = JSON.stringify(data.Items);
        statusCode = 200
    }catch(err){
        responseBody = `Unabel to get products: ${err}`;
        statusCode = 403
    }

    const response = {
        statusCode: statusCode,
        headers:{
            "Content-Type": "application/json",
            'Access-Control-Allow-Origin': '*', // new line
            'Access-Control-Allow-Credentials': true, // new line
        body: responseBody
    }

    return response
}

这是我使用 cloudformation 的 json 模板。

{
   "AWSTemplateFormatVersion": "2010-09-09",
         ...
   "Resources": {
         ...
     "getBannerHandler": {
       "Type": "AWS::Lambda::Function",
       "Properties": {
         "FunctionName": "getBanner",
         "Handler": "getBanner.handler",
         "Role": {
           "Fn::ImportValue": {
             "Fn::Sub": "${RolesStack}-LambdaRoleArn"
           }
         },
         "Code": {
           "S3Bucket": {
             "Ref": "HandlerCodeS3Bucket"
           },
           "S3Key":"getBanner.zip"
         },
         "Runtime": "nodejs12.x"
       }
     },
     "HelloWorldApi": {
       "Type": "AWS::ApiGateway::RestApi",
       "Properties": {
         "Name": "hello-api",
         "Description": "API used for practice",
         "FailOnWarnings": true
       }
     },
     "getBannerMethod": {
       "Type": "AWS::ApiGateway::Method",
       "DependsOn": ["HelloWorldApi"],
       "Properties": {
         "RestApiId": {
           "Ref": "HelloWorldApi"
         },
         "ResourceId": {
           "Ref": "BannerResource"
         },
         "HttpMethod": "GET",
         "MethodResponses":[
           {
             "ResponseModels" : {"application/json" : "Empty"},
             "ResponseParameters":{
               "method.response.header.Access-Control-Allow-Origin": "'*'"
             },
             "StatusCode" : "200"
           },
           {
             "StatusCode": "500"
           }
         ],
         "AuthorizationType": "NONE",
         "Integration": {
           "Credentials": {
             "Fn::ImportValue": {
               "Fn::Sub": "${RolesStack}-ApiGatewayRoleArn"
             }
           },
           "IntegrationHttpMethod": "POST",
           "IntegrationResponses": [{ 
             "ResponseParameters":{
                            "method.response.header.Access-Control-Allow-Origin": "'*'"
                          },  
              "StatusCode" : "200"
            }],
           "Type": "AWS_PROXY",
           "Uri": {
             "Fn::Join": ["",
               [
                 "arn:aws:apigateway:",
                 {
                   "Ref": "AWS::Region"
                 },
                 ":lambda:path/2015-03-31/functions/",
                 {
                   "Fn::GetAtt": ["getBannerHandler", "Arn"]
                 },
                 "/invocations"
               ]
             ]
           }
         }
       }
     }
   }
 }

如何处理此类问题?我发现我总是遇到这种问题。

更新:我的 API 网关

【问题讨论】:

    标签: amazon-web-services aws-lambda aws-api-gateway


    【解决方案1】:

    如果您想将 CORS 与 lambda/aws-proxy 集成一起使用,请记住在您的 headers 对象中包含 Access-Control-Allow-* 标头。

    例如

    'use strict';
    
    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://www.serverless.com/framework/docs/providers/aws/events/apigateway/

    【讨论】:

    • 我更新了上面的代码,但请检查这是否是您的意思。谢谢
    • 也添加此标头:'Access-Control-Allow-Credentials': true,
    猜你喜欢
    • 2017-04-28
    • 2021-06-29
    • 2020-10-23
    • 2019-06-10
    • 2022-06-15
    • 2017-04-11
    • 1970-01-01
    • 2013-11-29
    • 2014-07-28
    相关资源
    最近更新 更多