When requesting url image resources across domains, an error is reported: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present

1. Reason

Cross-domain is caused by the browser's "same-origin policy". As long as any of the host, port number, and protocol are different, cross-domain problems will occur.
Some Taoists will find that the same interface or request will not have such a problem when it is simulated in postman. This is because postman does not obey the same-origin policy, so there will be no cross-domain issues.

2. Phenomenon

The cross-domain error is shown in the figure belowinsert image description here

3. Solutions

1. Add Access-Control-Allow-Origin to the front-end request header

Add in the request header of this interface

'Access-Control-Allow-Origin': '*';

After the addition is successful, this line will appear on the request header when clicking the request interface
insert image description here

2. Add Access-Control-Allow-Origin to the backend response header

response.setHeader(Access-Control-Allow-Origin,"*");

Similarly, after the addition is successful, this line will appear on the response header when the request interface is clicked
insert image description here

3. OSS adds cross-domain settings

Click to log in to the oss background [https://oss.console.aliyun.com/] Select the Bucket list Select the Bucket to be set, select Data Security , and then select Cross-domain Settings , the specific operation is shown in the figure below. insert image description hereinsert image description here
Finally, click Edit or create a new rule to make the following settings
insert image description here

4. Check read and write permissions

5. nginx settings

First transfer the http picture to a picture under the local domain name, and then set the proxy by Nginx

 location ^~ /third_image/ {
    
    
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-  Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
    proxy_pass https://XXX.com/;
 }

Nginx setting reference: Nginx solves cross-domain problems has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present

4. Write at the end

Fellow Daoists, you can try methods 1-3 first to solve the problem. If it doesn't work, try the fourth method. The last method is a little simpler, so you can refer to the original text.

Guess you like

Origin blog.csdn.net/github_53963510/article/details/132100859