我有一个已部署的 Web 应用程序,它使用托管在 S3 上的 React 和 Redux 前端构建,以及托管在 AWS Lambda 上并通过无服务器部署的 API 网关公开的几个后端微服务。该站点还通过 CloudFront CDN 分发。
微服务与多个外部服务交互,但我最关心的是 get-products
查询 Stripe 产品数据库并将产品从那里返回到我的 React 应用程序的服务。
该站点一直运行良好,直到昨天我向前端部署了一些新的(基本上是装饰性的)更改,并向 Stripe 数据库添加了更多 SKU。自从添加这些更改后,我开始遇到以前没有的 CORS 错误。
最初我收到以下错误:
Access to XMLHttpRequest at 'https://XXXXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev/products' from origin 'https://www.superfunwebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
尽管我的 Lambda 响应包含以下 header :
'Access-Control-Allow-Origin': '*',
此时,我将 Lambdas 响应 header 更新为以下内容:
'Access-Control-Allow-Origin': 'https://www.superfunwebsite.com/',
'Access-Control-Allow-Credentials': true
该错误在很大程度上持续存在,除了在一个随机页面加载时,我收到一个错误,指出 Origin
https://www.superfunwebsite.com
和“访问控制允许来源”https://www.superfunwebsite.com/
不匹配。我已经将 Lambda 响应 header 更改为:
'Access-Control-Allow-Origin': 'https://www.superfunwebsite.com',
'Access-Control-Allow-Credentials': true
这似乎解决了异常的第二个错误。
但是,即使我使用像 Insomnia 这样的 HTTP 客户端进行测试,错误一仍然存在。我在回复中得到以下内容。
// status code
403
// response
{
"message": "Forbidden"
}
// headers
Content-Type: application/json
Content-Length: 23
Connection: keep-alive
Date: Tue, 18 Sep 2018 13:22:41 GMT
x-amzn-RequestId: eb691541-bb45-11e8-82ff-6d1b542dffb9
x-amzn-ErrorType: ForbiddenException
x-amz-apigw-id: NaxVLGJgjoEF5Fg=
X-Cache: Error from cloudfront
Via: 1.1 08037e15a3c6f503f39825efeb7f0210.cloudfront.net (CloudFront)
X-Amz-Cf-Id: cbNtb4xKWc48VPFon-Cl9y27KmXRVLIN5SWuYwNWlWsTXeaAXx3z-Q==
根据上面的 Insomnia 输出,我的问题似乎与 CloudFront 有某种关系,尽管我不明白具体是怎么回事。 This other S/O post似乎表明在 CloudFront 行为部分中应该有一些选项可以让我将响应的 header 列入白名单,但是这些选项在控制台中对我不可见,我已经看到了建议,这是因为源已打开S3.
我的问题很简单,是否有人知道我如何解决这个问题,或者是否还有其他我认为不应该考虑的问题?
最佳答案
在这里,您必须在 cloudfront 分发的行为部分中将相应的 CORS header 列入白名单。
Cache Based on Selected Request Headers
,选择白名单。 Access-Control-Request-Headers
和 Access-Control-request-methods
、 Origin
),然后选择添加。 上面的设置应该对你有用(因为它主要用于
GET
和 HEAD
),但如果没有,请使用下面的文章启用 OPTIONS 方法。请查看以下来自 aws 的文章:
no-access-control-allow-origin-error
Custom CORS Cloudfront
enhanced-cloudfront-customization
关于amazon-web-services - 使用 Lambda、API Gateway 和 Cloudfront 时,尽管在 Lambda 响应中指定了 'Access-Control-Allow-Origin',但 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52388132/