Introduction
In the previous article CORS Complete Guide (Part 1): Why CORS Error Occurs?, we understood why the browser has a same-origin policy and that the blocked cross-origin request is actually the response, not the request. After clarifying some misconceptions and having a basic understanding of CORS, we can now talk about how to solve CORS issues.
First of all, I want to let you know that the methods mentioned in this article are not complete solutions. In fact, cross-origin requests are divided into two types: simple requests and non-simple requests. The fact that “the blocked cross-origin request is actually the response, not the request” basically only applies to simple requests, and this article will only focus on “simple requests”. As for how to distinguish between simple and non-simple requests, and how to handle non-simple requests, these will be discussed in the next article.
There are actually many ways to solve basic CORS errors. Let’s first introduce a few “palliative” methods:
- Turn off the browser’s security settings.
- Set the fetch mode to no-cors.
- Do not use AJAX to fetch data.
After discussing these three methods, we will talk about the last and most correct method: “Add CORS header to the backend”.