在Serverless yml上配置CORS

18

我有一个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配置吗?


2
如果您正在使用lambda代理集成,则您的lambda代码需要将“Access-Control-Allow-Origin”标头添加到响应中。我认为在您的无服务器模板中没有其他地方需要放置与CORS相关的项目。 - Mike Patrick
1
我应该在yml文件中添加头部还是登录函数响应中添加头部? - Lee
1
在您的 Lambda 代码中,传递给 callback 的响应对象需要提供此标头。因此,您需要使用 {statusCode: 200, headers: {Access-Control-Allow-Origin: "*"}, body: {} } 而不是 {statusCode: 200, body: {} }。假设您正在使用 Lambda 代理集成。 - Mike Patrick
1
我添加了以下头部信息:{ 'Access-Control-Allow-Origin': 'https://admin. differentdomain.com', 'Access-Control-Allow-Credentials': true, } 但仍然无法正常工作。 - Lee
@Lee,你正在使用凭据。在你的serverless.yml文件中,你需要在cors:下添加allowCredentials: true而不是只写cors: true。在你的代码中添加头部也是必要的,所以请保留它。但这并不会被预检CORS请求调用,所以你还需要添加这个。 - V Maharajh
我有一个相同但完全不同的情况。我正在使用客户端发送的无效 x-api-key 值进行测试。这也导致了 No 'Access-Control-Allow-Origin' header is present on the requested resource. 我花了一个小时找出它与无效的 'x-api-key' 标头值有关。发送正确的密钥后,它就可以工作了。Lambda 函数中我需要返回的唯一标头是 "Access-Control-Allow-Origin": "*" - A.W.
2个回答

15

在Serverless中设置CORS的详细说明在这里:https://serverless.com/blog/cors-api-gateway-survival-guide/

除了serverless.yml中的配置(用于预检请求),您还需要从代码中返回头部Access-Control-Allow-OriginAccess-Control-Allow-Credentials。以下是您示例和Node.js实现:

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

请确保在第一个头部中包含 "https" 部分,我之前曾因此遇到问题。


1
我在使用私有端点时遇到了问题。我设置了`cors: true`,默认情况下`allowCredentials: false`。 相反,我必须像这样扩展cors字段:
functions:
  api:
    handler: main.handler
    events:
      - http:
          path: "/api/v1/{endpoint}"
          method: post
          private: true
          cors:
            origin: '*'
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
              - X-Amzn-Trace-Id
            allowCredentials: true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接