无服务器yml上的CORS

Lee*_*Lee 7 serverless-framework serverless aws-serverless

我有一个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.
Run Code Online (Sandbox Code Playgroud)

端点网址为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
Run Code Online (Sandbox Code Playgroud)

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

Ull*_*lli 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: {},
  };
Run Code Online (Sandbox Code Playgroud)

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