Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”. This article also participates in the “Digitalstar Project” to win the creation gift package and challenge the creation incentive money

Cors cross-domain principle

Cors stands for Cross-Origin Resource Sharing, which is an officially recommended cross-domain solution.

The cross-domain principle of Cors is that the browser and the backend server make some conventions and restrictions through some HTTP protocol headers.

The key to Cors communication is mainly in the back end. As long as the back end server implements THE Cors interface, it can communicate across domains.

Before cross-domains, the console displays an error 👇 when this page requests resources from other domains

The XMLHttpRequest (XHR) cannot request http://127.0.0.1:8080/user/selectUser, resources are not set in the response header Access – Control – Allow – Origin, so the Origin: http://localhost:8000 does not allow cross-domain requests.

When the back end responds to the cross-domain request, compare the request header Origin of the front end with the configured response header Access-Control-allow-Origin 👇

Access-control-allow-origin specifies which domain names can be used to request resources from the back end. The front-end browser can use access-Control-allow-Origin in Response Headers to see if it can spit out the data.

If the domain name specified by Origin is within the access-Control-allow-Origin range, the back end will return an Access-Control-allow-Origin message to the front end saying, “Cross-domain success!” ✌, back end can normally pass data forward.

This is how a simple cross-domain request is allowed, with only the response header set up at the back endAccess-Control-Allow-Origin.

Access-control-allow-origin: indicates the header field in which the back end sends cross-domain success feedback to the front end. The value is either the Origin field in the request header at the time of the front-end request, or an *, indicating that any domain name is accepted.

Simple and non-simple requests

Browsers classify Cors requests into two categories: simple and non-simple.

A simple request

As long as the following two conditions are met, it is a simple request.

  • The request method is one of three:head.get.post
  • HTTP headers do not exceed the following fields:
    • Accept
    • Accept-Language
    • Content-Language
    • Last-Event-ID
    • Content-type (Application/X-www-form-urlencoded, multipart/form-data, Text /plain)

For simple requests, the browser will send the Cors Request directly. Specifically (if you can read the above you already know 😎), the browser will add the Origin field to the Request Headers to indicate which source the Request is coming from. Then the back end compares the Origin sent from the front end with the access-Control-Allow-Origin which has been set up in advance to decide whether to agree to this request.

😫 If the source specified by Origin is not in the access-Control-allow-Origin range, the back end will return a normal HTTP response telling you that an error was made, The browser finds that the Response Headers message does not contain the Access-Control-Allow-Origin field. 👇

There is a special case 💣 : even if the request fails, the return status code may still be 200, indicating that the browser request was sent and the back end will return correctly, but we can’t get the response.

🤗 If the request is found on the backendOriginWithin the specified source range, the request result of the response is returned inResponse HeadersThe Cors header fields associated with backend Settings are returned, includingAccess-Control-Allow-OriginField information 👇

Non-simple request

Non-simple request, also called precheck request. Any request that does not meet both conditions is a non-simple request.

  • The request method is one of the following:put.delete.patch,connect,options,trace
  • The value of the content-type is not one of the following:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

When a request is not simple, the browser automatically sends an options request and sets the corresponding request header. If the request is found to be supported by the back end, the real request is sent to the back end, otherwise, if the browser finds that the back end does not support the request, it throws an error at the console, as follows:

If the non-simple request is successfully sent: 👇

The blue box indicates the query sent by the pre-check Request. The Access-Control-request-headers and access-Control-request-method fields are added to the Request Headers field. The back-end supports pre-checking requests before the actual request is sent (shown in the red box). Access-control-allow-origin = access-Control-allow-origin = access-Control-allow-origin = access-Control-allow-origin

Response header field instructions
Access-Control-Allow-Headers Indicates the custom request header field carried with the request
Access-Control-Allow-Methods Indicates the request method supported by the back end
Access-Control-Max-Age Indicates the Cors cache time, that is, the validity period of this request, in seconds. In the meantime, another precheck request will not be issued.

Write in the back

Jsonp cross-domain VS Cors cross-domain

The json cross-domain Cors cross-domain
Browser support is good Cors is supported by most browsers. Browsers below Internet Explorer 10 do not support Cors
Can only sendgetRequesting resources Support for all types of HTTP requests (get,post,put,deleteEtc.)
Error handling mechanism is not perfect, if the dynamic injection of JS script is successful, the callback function will be executed, if there is an error without any message You can listen for errors through the onError event, and the browser console can see a detailed error message, easy to troubleshoot
Cross-domain success requires the cooperation of both the front-end and back-end The front end sends requests as usual, but the back end is mostly busy
The request will only be sent once Non-simple Cors requests are sent twice (precheck request + actual request)
Callback parameter injection and resource access authorization Settings have security issues Resource access authorization (Access-Control-Allow-Origin) to restrict
Only resources can be read after being attacked It can not only read resources after being attacked, but also modify them

Summarize the protocol headers associated with Cors across domains

Request Headers field instructions
Origin The current request source, automatically generated when the request is sent
Access-Control-Request-Method Prechecking the request exclusively tells the back end the HTTP method used for the actual request
Access-Control-Request-Headers Precheck the request exclusively, telling the back end the header field carried by the actual request
Response Headers field instructions
Access-Control-Allow-Origin The back end gives the front end feedback on the cross-domain success of the response header field. Its value is either in the request header when the front end requests itOriginThe value of the field, or one*To accept requests from any domain name.
Access-Control-Allow-Headers Indicates the custom request header field carried with the request
Access-Control-Allow-Methods Indicates the request method supported by the back end
Access-Control-Max-Age Indicates the Cors cache time, that is, the validity period of this request, in seconds. In the meantime, another precheck request will not be issued.
Access-Control-Allow-Credentials Indicates whether sending is allowedcookie. By default, browsers do not send cookies when Cors requests cross domains. If you need to pass across domainscookie.The front endYou need to set upwithCredentials:trueAnd at the same timeThe back-endYou also have to setAccess-Control-Allow-Credentialsfortrue.
Access-Control-Expose-Headers When Cors requests,XMLHttpRequestThe object’sgetResponseHeader()The method only gets six basic fields:Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma. If you want to get the other fields, you have to be inAccess-Control-Expose-HeadersSpecify inside.

Solo understands, if there is anything wrong with the above, please kindly advise ~

References:

Cors implementation request cross domain – resourceful Mr. Zhao

One article to understand CORS cross-domain (front-end + back-end code example)- Jasmine tea only