Using Fetch with 'no-cors' Mode
The Fetch API provides a convenient way to make requests to servers. However, when accessing resources cross-origin, you may encounter the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." This error indicates a security restriction imposed by Same-Origin Policy.
To disable CORS in Fetch, it is tempting to use the { mode: 'no-cors' } option. However, this approach is incorrect and undesirable.
'no-cors' Mode: A Misstep
'no-cors' mode essentially prevents the browser from accessing the response body and headers. This means your code will not be able to process or use the fetched data. It is crucial to understand that disabling CORS does not override the Same-Origin Policy. It only affects how the browser handles the response.
The Solution: CORS Proxy
Instead of disabling CORS, you should use a CORS proxy. A proxy acts as an intermediary between your frontend code and the target server. When you send a request through a proxy, it forwards the request to the server, receives the response, and adds the necessary Access-Control-Allow-Origin header before passing it back to your code. This allows your code to access the response cross-origin.
To set up a CORS proxy, you can use existing services or deploy your own proxy using platforms like Heroku.
Understanding Cross-Origin Requests
It's important to note that even if you can access resources cross-origin in Postman, browsers impose restrictions on frontend code running in web apps. To ensure cross-origin resource access, the response must include the Access-Control-Allow-Origin header.
Opaque Responses: Caveats
While 'no-cors' mode disables CORS, it also creates opaque responses. Opaque responses have certain limitations, including:
Therefore, using 'no-cors' should be considered only in specific situations, such as caching and embedding resources in certain HTML elements.
Conclusion
Disabling CORS with 'no-cors' mode is not the solution for cross-origin resource access. Instead, using a CORS proxy is the preferred approach. By bridging the gap between your frontend and the target server, a proxy adds the necessary header, enabling your code to work seamlessly across origins.
The above is the detailed content of Why is using Fetch's 'no-cors' mode not the solution for handling cross-origin requests?. For more information, please follow other related articles on the PHP Chinese website!