我正在使用AWS S3,并且我配置了我的水桶以使用CORS:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
我在客户端的React应用程序中要求从存储桶中的SVG图像。我正在将它们渲染为内联,因此响应需要启用CORS标题。有时这有效,有时无效。我无法完全隔离导致问题的原因。我正在检索一张图像。然后,我将新图像上传到了存储桶中,一旦下载,该图像就会给我错误:
XMLHttpRequest cannot load https://s3.amazonaws.com/.../example.svg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我尝试添加<AllowedHeader>*</AllowedHeader>
和<ExposeHeader>ETAG</ExposeHeader>
,并在每次更改中清除缓存,但无效。我很困惑。标题为什么不通过?
它并不总是返回CORS标题,似乎您需要提供一个原始标题,并且并不总是这样做。
要使其保持一致并始终返回CORS标题,您需要添加一个lambda功能:
'use strict';
// If the response lacks a Vary: header, fix it in a CloudFront Origin Response trigger.
exports.handler = (event, context, callback) => {
const response = event.Records[0].cf.response;
const headers = response.headers;
if (!headers['vary'])
{
headers['vary'] = [
{ key: 'Vary', value: 'Access-Control-Request-Headers' },
{ key: 'Vary', value: 'Access-Control-Request-Method' },
{ key: 'Vary', value: 'Origin' },
];
}
callback(null, response);
};
请参阅此处的完整答案和更多详细信息:https://serverfault.com/a/856948/46223