When requesting a AWS cloudfront resource encounter a error message as following
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Run the following command to verify that the original server returns the Access-Control-Allow-Origin header
curl -H "origin: https:/example.xyz.com" -v https://cdntest.xyz.com/web/app.661cd60e.css
If the CORS policy allows the origin server to return an Access-Control-Allow-Origin header, you should see a response similar to the following:
HTTP/1.1 200 OK
Content-Type: text/css
Content-Length: 214460
Connection: keep-alive
Date: Fri, 10 Mar 2023 03:55:11 GMT
Access-Control-Allow-Origin: https:/example.xyz.com
Access-Control-Allow-Methods: GET, PUT
Access-Control-Expose-Headers: x-amz-server-side-encryption, x-amz-request-id, x-amz-id-2
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Last-Modified: Fri, 10 Mar 2023 01:54:13 GMT
ETag: "fda6fd1d53b39d86b32b740d36c1b879"
x-amz-server-side-encryption: AES256
Accept-Ranges: bytes
Server: AmazonS3
Vary: Accept-Encoding
X-Cache: Hit from cloudfront
If the CORS header is not returned in the response, the original server did not set CORS correctly. Due to eh orginal server is Amazon S3, you need check S3 configuration. How to configure S3 cors
Step1 configure CloudFront forward fllowing header key to original server S3
- Access-Control-Request-Headers
- Access-Control-Request-Method
- Orgin
To forward above headers to the source server, CloudFront's two predefined policies can be used depending on the source type CORS-S3Origin and CORS-CustomOrigin
Step2 attach the policy to behavior,follow the steps.
- Jump to AWS cloudfront distributions
- Select Behavior option
- Edit behavior
- In Cache key and origin requests select Cache policy and origin request policy
- In Origin request policy, select CORS-S3Origin or CORS-CustomOrigin
- About cache policy, following create a cache policy.
- Save
step3 Create cache policy.
When I choose a predefined, CachingOptimized, the issue comes up at the beginning of the article
To forward headers using the cache policy, do the following:
- create a custom policy
- At Cache key settings, select Include the following headers for headers. From the Add header drop-down list, select the required header for a source. At step 1, three header add to the header
- save policy
- repeate step2, attach the cache policy you have created
- save
Validate on chrome browser
As you want test from origin site such as www.eg1.com,take the following steps:
-
open it with chrome browser.
-
find the inspect
-
input the follow text in the console
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://www.example.com/news/xx.css'); xhr.send(null); xhr.onload = function(e) { var xhr1 = e.target; console.log(xhr1.responseText); }
评论区