preface
For front-end development, CORS should be a very important issue, but for most projects, it is the same as the front and back end, so CORS will not be involved. Even in the interview, most people only know the general, no one goes into the details of the implementation.
It wasn’t until recently that I looked up some information and learned more about the mechanics of CORS after encountering problems in the development process. So this article is for front-end developers who have had similar experiences, focusing on the problems encountered in practice. At the end of the article, the back and forth end codes are provided for reference.
What is the CORS
Before we get to CORS, we need to understand how browsers load resources:
- The same-origin policy, which is the same origin of two urls
Protocol, port (en-us) (if specified), and host are the same
If so, the two urls arehomologous. The same origin policy is an important security policy. It can limit the interaction between resources, block malicious documents, and reduce the media that can be attacked. - As opposed to the same origin policyAcross the source“, as we often sayCross domainAs long as
Protocol, port, and host have one difference
Is cross-domain.
The table below gives the with URL store.company.com/dir/page.ht… Source for comparison:
URL | The results of | why |
---|---|---|
Store.company.com/dir2/other…. | homologous | Only the path is different |
Store.company.com/dir/inner/a… | homologous | Only the path is different |
store.company.com/secure.html | Across the source | Agreement is different |
Store.company.com: 81 / dir/etc. HTM… | Across the source | Different ports (http://default port is 80) |
News.company.com/dir/other.h… | Across the source | The host different |
The same origin policy is not covered here, but for most projects the same origin is not a problem. However, in the case of cross-domain issues arising from the current back-end split deployment, we can use CORS to solve the problem because browsers limit cross-domain requests for security reasons.
CORS is cross-origin Resource Sharing, Chinese translation of cross-domain Resource Sharing. The CORS mechanism allows the server to allow browsers to access these cross-domain resources by identifying domains other than its own, and is a common solution to cross-domain problems.
(I’m sure most people will open their mouths to cross-domain solutions in an interview, but not always in practice, so the proof is in the pudding)
As an aside, CORS is an important knowledge point in the front end, but I think the back end should also have enough understanding of it, otherwise there will be the awkward situation that the front end students require to configure CORS, but the back end students do not know how to do it. (Don’t ask me why I know.) After all, this is a front-and-back job.
Simple request vs. precheck request
In CORS specification, talk request is divided into two kinds, namely simple request and precheck request.
Simple requests are defined as follows:
- Use method:
GET
,HEAD
,POST
One of the - Allow artificial header fields (i.e., CORS safe header fields)
- Accept
- Accept-Language
- Content-Language
- Content-type (with additional restrictions)
- DPR
- Downlink
- Save-Data
- Viewport-Width
- Width
- Any of the requests
XMLHttpRequestUpload
None of the objects are registered with any event listeners;XMLHttpRequestUpload
Objects can be usedXMLHttpRequest.upload
Property access - Not used in the request
ReadableStream
object
The value of Content-type can only be one of the following:
- text/plain
- multipart/form-data
- application/x-www-form-urlencoded
A request that meets the preceding conditions is a simple request.
A request that does not meet the above criteria is triggeredPreview the request. The browser must be used firstOPTIONS
Method to know whether the server will allow the cross-domain request. Prechecking requests “prevents cross-domain requests from having an unexpected impact on the server. An example of a precheck request is shown below: The request is fromlocalhost:8080
Sent to thelocalhost:3000
A GET request for a different port, resulting in a cross-domain request. But because of the request headerheader
Contains a custom fieldX-Custom-Header
, so the precheck request is triggered, and the GET request is made only after the precheck request passes.
A request carrying a Cookie
CORS can send identity credentials based on HTTP cookies and HTTP authentication information. Typically, browsers do not send credentials for cross-domain requests. To send credential information, you need to set the following parameters:
The client can send the request with Cookie to the server only after the following Settings:
withCredentials: true
Copy the code
The server needs to set the response header:
Access-Control-Allow-Credentials: true
Copy the code
If the server is not set, the browser will not return the response.
Note that the server cannot set requests that require cookiesAccess-Control-Allow-Origin
The value of*
In which case the request will fail, as shown below:
CORS set
Here are some common CORS Settings.
HTTP response header field
Access-Control-Allow-Origin
This field specifies the outdomain URI that is allowed to access the resource:
Access-Control-Allow-Origin: http://localhost:8080
Copy the code
The above Settings allow requests from http://localhost:8080 to access the resource. The wildcard * can also be set to allow requests from all domains to access the resource. You can specify wildcard values for requesting servers that need to carry cookies.
Note: Access-Control-allow-origin does not support multiple Origin Settings. Only one Origin or * can be specified. Passing more than one comma-separated orgin returns an error:
Access-Control-Expose-Headers
In cross-source access, the getResponseHeader() method of the XMLHttpRequest object takes only the most basic response headers. Only seven response headers can be exposed externally by default:
Cache-Control
Content-Language
Content-Type
Content-Length
Expires
Last-Modified
Pragma
If you want to access other headers, you need the server to set this response header.
Access-Control-Expose-Headers: X-Kuma-Revision, X-Custom-Header
Copy the code
The above Settings expose two custom response headers to the browser. Let’s take a look at the following example:
The server defines an X-expose-headers response header, but does not set access-Control-expose-headers, so even if the browser prints a response object, it is not available in Headers.
Access-Control-Max-Age
Used to specify how long the results of a precheck request can be cached.
Access-Control-Max-Age: 3600
Copy the code
The above setting means that the result of the precheck request will be valid for 3600 seconds.
Access-Control-Allow-Credentials
Used to specify whether the browser is allowed to read the contents of the response when the browser credentials are set to true. When used in response to pre-checked requests, it specifies whether the actual request can use credentials, as described in the previous section.
Access-Control-Allow-Methods
Used to precheck the response to the request. Specifies the HTTP methods allowed for the actual request.
Access-Control-Allow-Methods: PUT, GET, POST, DELETE
Copy the code
The above Settings indicate that the request is allowed to be called using the PUT, GET, POST, and DELETE methods.
Access-Control-Allow-Headers
Used to precheck the response to the request. This specifies the header field that is allowed in the actual request.
Access-Control-Allow-Headers: token, originalUrl
Copy the code
The above Settings indicate that header fields named token and originalUrl are allowed in actual requests.
HTTP request header field
The header fields that can be used to make cross-domain requests are listed below and do not need to be manually set by the developer.
Origin
The Origin field indicates the source of the precheck request or the actual request.
Note that the Origin header field is always sent in all Access Control requests.
Access-Control-Request-Method
Used to pre-check requests to tell the server the HTTP method used for the actual request.
Access-Control-Request-Headers
Used to precheck requests. This tells the server the header field carried by the actual request.
The DEMO source code
Github.com/Yayoiqz/cor… The above CORS Settings are available in the DEMO and can be debugged.
reference
- Cross-source Resource Sharing (CORS)
- In-depth understanding of CORS