1. What are cross-domain issues
To understand the cross-domain problem, we must first understand the browser’s same-origin policy, which simply means that if two addresses have different protocols, ports, and hosts, the browser will restrict the resource interaction between the two addresses. The advantage of doing this is to avoid CSRF attacks for security reasons.
Second, there are problems
In project development, it is often encountered that a front-end page will request resources from multiple different domain names, and the same origin policy will restrict the request, leading to the failure of the request, so how to bypass it? Here we do not discuss some front-end practices, because I am back-end development, focus on the need for back-end involvement of CORS to solve cross-domain problems.
Third, CORS
CORS is a W3C standard, which stands for cross-origin Resource Sharing.
Browsers classify cross-domain requests into two types: simple and non-simple.
3.1 Simple Request
As long as the following two conditions are met, it is a simple request.
origin
Access-Control-Allow-Origin
The value of this field is the source of the request, or an * to indicate that all cross-domain requests are allowed
Access-Control-Allow-Credentials
The value of this field can be true, indicating that cookies are allowed to be sent. When this field is true, access-Control-allow-origin cannot be *; otherwise, an error is reported.
The browser knows that the cross-domain request is allowed when it receives a response header with the above message.
3.2 Non-simple Requests
A non-simple request is one that does not meet the conditions for a simple request. The special feature of non-simple requests is that a precheck request is sent to confirm whether the backend allows the precheck request before formal communication. The precheck request will contain the following fields:
Access-Control-Request-Method
This field is required to list which HTTP methods, such as PUT, will be used for browser CORS requests
Access-Control-Request-Headers
When a request needs to send a custom header field in the request header, this field carries the custom header field name
When the back end receives a precheck request and allows cross-domain processing, the following fields need to be added to the response header:
Access-Control-Allow-Methods
Mandatory, returns all supported request methods
Access-Control-Allow-Headers
This field is mandatory if the Request header includes access-Control-request-headers. All supported Request header fields are returned
Access-Control-Allow-Credentials
I already said that. I won’t repeat it
Access-Control-Max-Age
Optional field that specifies the validity period of the precheck request during which the precheck does not need to be repeated.
When the precheck request passes, it is treated like a simple request.