【问题标题】:dynamic Access-Control-Allow-Origin header serverless动态 Access-Control-Allow-Origin 标头无服务器
【发布时间】:2020-10-18 19:43:19
【问题描述】:

我已经配置了如下的无服务器功能

id:
  handler: id.get
  events:
    - http:
        path: id
        method: get
        cors:
          origin: ""
          headers:
            - Content-Type
            - X-Amz-Date
            - Authorization
            - X-Api-Key
            - X-Amz-Security-Token
            - x-access-token
          allowCredentials: true

我的处理函数中的代码如下

let headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': event.headers.Origin ? event.headers.Origin : event.headers.origin,
  'Access-Control-Allow-Credentials': true
}
callback(null, {
  "isBase64Encoded": false,
  "statusCode": 200,
  "headers": headers,
  "body": JSON.stringify(body),
  "multiValueHeaders": multiValueHeaders
})

我收到了对OPTIONS 请求的回复

access-control-allow-origin: *
access-control-allow-credentials: true

因此我收到以下错误

从源“http://localhost:8080”访问“https://example.com/dev/id”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

我希望Access-Control-Allow-Origin 应该是动态的(请求的来源),我该如何解决这个问题?

【问题讨论】:

    标签: aws-lambda cors aws-api-gateway amazon-cloudfront serverless


    【解决方案1】:

    我用下面的代码创建了一个新方法options

    module.exports.options = async (event, context, callback) => {
      const origin = event.headers.Origin || event.headers.origin;
      context.succeed({
        headers: {
          "Access-Control-Allow-Headers": "Accept,Accept-Language,Content-Language,Content-Type,Authorization,x-correlation-id,x-access-token",
          "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS",
          "Access-Control-Allow-Origin": origin ? origin : '*',
          "Access-Control-Allow-Credentials": true
        },
        statusCode: 204
      });
    };
    

    serverless.yml

    options:
      handler: id.options
      events:
        - http:
            path: id
            method: options
    

    【讨论】:

      【解决方案2】:

      更改此配置:

      id:
        handler: id.get
        events:
          - http:
              path: id
              method: get
              cors:
                origin: "*"
                headers:
                  - Content-Type
                  - X-Amz-Date
                  - Authorization
                  - X-Api-Key
                  - X-Amz-Security-Token
                  - x-access-token
                allowCredentials: true
      

      【讨论】:

      猜你喜欢
      • 2016-01-11
      • 2014-05-05
      • 2019-02-07
      • 2018-01-24
      • 2014-07-23
      • 2018-10-28
      • 2016-01-21
      • 2018-07-18
      • 2019-03-18
      相关资源
      最近更新 更多