CORS前提
为了能够正确返回相应头,首先需要通过以下三点来验证
- 请求源的允许Access-Control-Allow-Origin响应头
- CloudFront分配转发相关的标头
- CloudFront分配的缓存行为允许HTTP请求的OPTIONS方法
配置步骤
在S3的桶对应权限配置允许的cors响应头
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"HEAD",
"GET",
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 88888888
}
]
然后在cloudfront配置缓存策略,在策略选项卡,创建一个策略,确保以下信息正确填写
设置TTL,Headers选择Whitelist后配置Origin
,Access-Control-Request-Method
,Access-Control-Reqeust-Headers
即可
配置完成后可以通过curl命令进行验证
curl -H "origin: kelen.com" -v "https://www.xxx.com/xxx.jpg"
配置成功后就会返回以下信息
< HTTP/2 200
< content-type: image/jpeg
< content-length: 93073
< date: Tue, 19 Jan 2021 06:33:56 GMT
< access-control-allow-origin: *
< access-control-allow-methods: HEAD, GET, PUT, POST, DELETE
< access-control-expose-headers: x-amz-server-side-encryption, x-amz-request-id, x-amz-id-2, ETag
< access-control-max-age: 3000
< last-modified: Sat, 12 Sep 2020 09:55:43 GMT
< etag: "87e9495aee75c14a6632aeaddcdaee46"
< accept-ranges: bytes
< server: AmazonS3
实战经验
在canvas绘制图片的时候,经常会报跨域问题,只需要针对img标签设置 origin="anonymous" 就可以解决这个问题
注意,CloudFront需要在请求头需要带上origin才会返回对应的cors相关对响应头
本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系340443366@qq.com