What Is CORS? Why Using CORS?
October 4, 2022
CORS-related errors are common when calling a API. Do you know why does the error exist? How to fix it? These are also common questions in the interview.
Start with the Same Origin Policy
Before understanding why there is CORS, we need to understand the browser's same-origin policy (same origin policy). Browsers have some security policies to ensure the security of information transmission. **Same Origin Policy is one of the security-related specifications, which restricts **webpages to only access resources of the same origin.
Same origin must meet the following three conditions:
- Same communication protocol (protocol)
- Same domain (domain)
- Same communication port (port)
Taking https://www.explainthis.io
as an example, we use the same-origin standard to look at the following examples, and we can see which ones belong to the same origin or non-same origin
1. https://www.explainthis.com // Different domains (domain), not the same origin
2. http://www.explainthis.io // Different communication protocols (protocol), non-homologous
3. http://www.explainthis.io:5000 // different communication ports (port), non-same source
4. http://www.explainthis.io/ilikejavascript // same source
5. http://www.hello.explainthis.io // non-homologous
So when https://www.explainthis.io
wants to access non-homologous resource sources, for example: https://www.explainthis.com/blog/1
, then browser CORS will appear error. As shown below:
Here you can think about why there is a security specification of the same-origin policy? What does it protect
The same-origin policy restricts non-same-origin requests, so what problems will non-same-origin requests cause? Suppose a user logs in to a bank website www.bank.com
today, and he happens to be using another non-same-origin request. A secure website such as www.stolemoney.com
, if there is no same-origin policy, this stolemoney
website may easily access the user's data in www.bank.com
.
The browser's same-origin policy is like the most basic layer of protection mechanism, preventing websites from different origins from accessing resources and data. In addition, it should be noted that this blocking mechanism occurs after the browser receives the server-side response; that is, even if it is a non-same-origin request, if the server does not do any blocking and returns the result, the browser In fact, the client will successfully receive the response, but because it violates the same-origin policy, the browser will intercept the response and report an error.
Solve non-same-origin access - through CORS
In the previous paragraph, we know that the browser's same-origin policy can provide a protection net, but in practical development, we almost inevitably request non-same-origin resources. In the case of a same-origin policy, how to make non-same-origin requests? That's right, through CORS.
CORS stands for **Cross-Origin Resource Sharing. **To achieve CORS, the cooperation of the requesting end and the server end will be required. When the resource to be obtained is not of the same origin, the browser will automatically initiate a cross-domain (CORS) request. If the requested server has an additional HTTP header (Header) to tell the browser that it is allowed to be accessed by this domain, So when the interviewer asks "How to solve the CORS problem", the most direct answer is "Please ask the back-end engineer to set the CORS header on the server side". As for how to set it, let us continue to read.
Simple requests
The entire process of CORS is divided into simple request and **preflight request. Basically, requests are all preflight requests. Only when ** meets certain conditions (for example, using GET
, HEAD
, POST
method) will be **Simple requests. The ** conditions that meet the simple request also include the set header, the header value of Content-Type
, etc. For detailed specifications, please refer to [MDN](https://developer.mozilla.org/zh-TW/ docs/Web/HTTP/CORS#%E7%B0%A1%E5%96%AE%E8%AB%8B%E6%B1%82).
In the case of a simple request, the browser will directly send the request to the server and include the origin in the header
Origin: https://www.explainthis.io
Then, the server responds with Access-Control-Allow-Origin
in the header plus allowed origins, or an asterisk for all origins. The Access-Control-Allow-Origin
here is the key. As mentioned in the previous paragraph, when encountering CORS problems, please ask the back-end engineer to set it. The setting to be done is the Access-Control-Allow-Origin
setting. Example as follows.
// If you want to allow all cross-origin requests, you can use an asterisk
Access-Control-Allow-Origin: \*
// If you want to allow cross-origin requests from a specific origin, you can put this origin directly
Access-Control-Allow-Origin: https://www.explainthis.io
Preflighted requests
As long as the conditions of the simple request are not met, the browser will first make an HTTP request, called preflight request (preflight), the method of the preflight request is OPTIONS
, once the preflight request is successfully completed, the real request will be sent. However, the preflight request may not be triggered every time. When the server responds to the preflight request, it can be in [Access-Control-Max-Age](https://developer.mozilla.org/en-US/docs /Web/HTTP/Headers/Access-Control-Max-Age) header with the number of seconds to cache the preflight request response, that is, within this number of seconds, the preflight request will be cached, no need Retrigger can send actual request directly like simple request.
It is also very common to be asked during the interview, "Why do you need a pre-check request? Wouldn't it be a waste of resources to make one more request before the official request?" To this question, we can first answer from the perspective of security. The previous paragraph has As mentioned, the same-origin policy will only block the response, not the request, so if a malicious attacker sends a DELETE
request, the same-origin policy will not block the request (if there is a response after the request, the part of the response In other words, if there is no additional layer of filtering, malicious attackers may randomly delete resources on the server side by sending DELETE
requests. With the pre-check request, it is equivalent to an additional layer of filtering. When the pre-check request passes, the real request will be sent to the server.
In addition to security, compatibility is also a point of pre-check request assistance confirmation, because web development technology iterates very quickly, and many new technologies are not supported on old websites. If the browser sends a request that is not supported by the server , which may cause problems on the server side. At this time, the pre-check request will be a protection. First ensure that the server has support before actually sending the request.