无服务器 yml 上的 CORS

问题描述 投票:0回答:2

我有一个 React 应用程序,并尝试从 aws 访问无服务器。但我有以下错误

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.test.com' is therefore not allowed access. The response had HTTP status code 502.

端点网址为 https://key.execute-api.ap-southeast-2.amazonaws.com/dev/samplefunction

serverless.yml 上的设置是

login:
    handler: login.login
    events:
      - http:
          path: login
          method: post
          cors:
            origin: 'https://admin.differentdomain.com'
            headers:
              - MY_CUSTOM_HEADER
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token

还有其他地方需要进行CORS配置吗?

serverless-framework serverless aws-serverless
2个回答
15
投票

无服务器中的 CORS 设置详细说明如下:https://serverless.com/blog/cors-api-gateway-survival-guide/

除了 serverless.yml 中的配置(用于预检请求)之外,您还需要从代码中返回标头

Access-Control-Allow-Origin
Access-Control-Allow-Credentials
。在您的示例和 Node.js 实现中:

  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': 'https://admin.differentdomain.com',
      'Access-Control-Allow-Credentials': true,
    },
    body: {},
  };

确保在第一个标头中包含“https”部分,我之前偶然发现过这一点。


0
投票

我在使用 FastAPI 解决这个问题时遇到了问题,但我通过在

OPTIONS
方法上专门启用 CORS 来解决它。

所以 API 与 FastAPI 文档相同:

# main.py
app = FastAPI(version='0.1')
app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["POST", "OPTIONS"],
        allow_headers=["*"]
)
handler = Mangum(app)

重要部分,在

serverless.yaml

functions:
  api:
    handler: main.handler
    events:
      - http:
          path: "/{endpoint}"
          method: post
          cors: true
      - http:
          path: "/{endpoint}"
          method: options
          cors: true
© www.soinside.com 2019 - 2024. All rights reserved.