Understanding the "No 'Access-Control-Allow-Origin' Header" Error
When encountering an error message like "No 'Access-Control-Allow-Origin' header is present on the requested resource," it indicates that your browser is restricting the cross-origin resource sharing (CORS) between your script and the server. Here's a breakdown of the issue and how to resolve it.
What is CORS?
CORS is a mechanism that regulates the exchange of information between scripts from different origins (domains). Without CORS, only same-origin requests (scripts and servers from the same domain) are permitted for security reasons.
The "No 'Access-Control-Allow-Origin' Header" Error
When making a cross-origin request, the browser sends a special header named "Origin" with the request. If the target server does not respond with a corresponding header "Access-Control-Allow-Origin," the browser blocks the request for security reasons.
Solution: Adding the "Access-Control-Allow-Origin" Header
To resolve this issue, you need to add the "Access-Control-Allow-Origin" header to the server's response. This header specifies which domains are allowed to access the resource.
Using addHeader Method
Instead of using the setHeader method, employ addHeader to set the header:
response.addHeader("Access-Control-Allow-Origin", "*");
Setting "*" in the header grants access to all domains.
Allowing Specific Domains
For specific domain access, use:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
Reference Links
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3