首页 > 解决方案 > 无服务器启用 CORS

问题描述

如何在无服务器中启用 CORS?

在调用我的 lambda 函数时,我不断收到以下错误消息。

No 'Access-Control-Allow-Origin' header is present on the requested resource.

我到处搜索,我仍然无法弄清楚如何解决它。任何帮助将不胜感激!!!

这是我的设置:

我的 Python 处理程序,经过测试serverless invoke local

def main(event, context):
    ...operations with pandas...

    return {
        'statusCode': 200,
        'headers': {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': True
        },
        'body': json.dumps(response),
    }

我的 serverless.yml

functions:
  main:
    handler: handler.main
    events:
      - http:
          path: dashboard
          method: get
          authorizer: aws_iam
          cors: true

我的前端,一个 React 应用程序。API 调用是使用 aws-amplify 进行的:

try{
  const myInit = {
    body: JSON.stringify(this.props.session),
    headers: {
      "Content-Type": "application/json"
    }
  };
  const calculation = await API.get("clearly", "/dashboard", myInit)
  console.log(calculation);
} catch(e) {
  ...
}

谢谢!

编辑:

当我尝试在 API Gateway 中手动启用 CORS 时,我收到了这个Invalid Response status code specified错误消息。 捕获

标签: corsaws-api-gatewayserverless-frameworkaws-amplify

解决方案


您是否使用模拟集成类型创建了 OPTIONS 方法以返回像这样的响应标头

Access-Control-Allow-Methods Access-Control-Allow-Headers Access-Control-Allow-Origin

只需参考(https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html


推荐阅读