Cross domain access is realized through JSONP, CORS and proxy

When the browser executes the JS script, it will check whether the protocol, domain name and port number to be accessed by the script are consistent with the current web address. If not, it is cross domain. Cross domain is not allowed. This restriction is called the browser's homology policy. In a simple way, the browser does not allow scripts loaded in one source to interact with resources in other sources. So how to implement cross domain?

JSONP, CORS mode, proxy mode

1. JSONP mode

Tags with src attributes such as script, img, iframe, link, video and audio can request and execute resources across domains. JSONP uses this "vulnerability" to achieve cross domain.

<script>
    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = "http://10.10.0.101:8899/jsonp?callback=f";
    document.head.appendChild(scriptTag);
</script>

Let's look at the way jQuery is written.

$.ajax({
    // Request domain name
    url:'http://10.10.0.101:8899/login',
    // Request mode
    type:'GET',
    // Data type selection jsonp
    dataType:'jsonp',
    // Callback method name
    jsonpCallback:'callback',
});
// Callback method
function callback(response) {
console.log(response);
}

JSONP is simple to implement across domains, but only supports GET requests. Moreover, after receiving the JSONP request, the server needs to set the request header and add the access control allow origin attribute. The attribute value is *, which means that all domain names are allowed to access, so that the browser can resolve normally, otherwise 406 error will be reported.  

response.setHeader("Access-Control-Allow-Origin", "*");

2. CORS mode

Cross origin resource sharing (CORS) refers to cross domain resource sharing, which requires the support of both browser and server. This request method is divided into simple request and non simple request.
When the request mode of XMLHttpRequest sent by the browser is POST or GET, and the request header only contains Accept, Accept language, content language, last event ID and content type (application/x-wwwform-urlencoded, multipart / form data, text/plain), then the request is a simple request.
For simple requests, the browser will add the Origin attribute in the request header to indicate which source the request comes from (protocol + domain name + port).  

GET
// Indicate which source this request comes from (protocol + domain name + port)
Origin: http://127.0.0.1:8080
// IP
Host: 127.0.0.1:8080
// Long connection
Connection: keep-alive
Content-Type: text/plain

If the domain name indicated by Origin is within the license range of the server, the server will respond:

// As mentioned above, this value indicates that the domain name specified by the browser is allowed to access, either the origin passed in by the browser or * indicates
 All domain names are accessible
Access-Control-Allow-Origin: http://127.0.0.1:8080
// Indicates whether the server allows the browser to send cookie s
Access-Control-Allow-Credentials: true
// Specify the fields that can be obtained by the XMLHttpRequest#getResponseHeader() method
Access-Control-Expose-Headers: xxx
Content-Type: text/html; charset=utf-8

Access control allow credentials: true indicates that the server agrees with the browser to send cookies. In addition, the browser also needs to be set to support sending cookies. Otherwise, even if the server supports the browser, it will not send cookies.  

var xhr = new XMLHttpRequest();
// Set whether to send a request with a cookie
xhr.withCredentials = true;
xhr.open('post', 'http://10.10.0.101:8899/login', true);
xhr.setRequestHeader('Content-Type', 'text/plain');

The other is a non simple request. The request method is PUT or DELETE, or Content is added to the request header-
Type: request for application / JSON attribute and attribute value. This kind of request will send a pre check HTTP request before the browser officially sends out the XMLHttpRequest request, asking whether the domain name of the current web page of the server is in the license list of the server. The communication request will be officially sent only after it is confirmed by the server.
Header information of pre inspection request:

// The request method of pre inspection request is OPTIONS
OPTIONS
// Indicate which source this request comes from (protocol + domain name + port)
Origin: http://127.0.0.1:8080
// Indicate the request mode to be used for the next CORS request
Access-Control-Request-Method: PUT
// Indicates the header information attribute to be attached to the next CORS request
Access-Control-Request-Headers: X-Custom-Header
// IP
Host: 127.0.0.1:8080
// Long connection
Connection: keep-alive

If there is no CORS related header information in the response header of the server responding to the pre inspection request, it means that cross domain is not supported. If cross domain is allowed, the server will respond. The response header information is as follows:

HTTP/1.1 200 OK
// As mentioned above, this value indicates that the domain name specified by the browser is allowed to access, either the origin passed in by the browser or * indicates that all domain names can be accessed
Access-Control-Allow-Origin:http://127.0.0.1:8080
// All cross domain request modes supported by the server. In order to prevent the browser from initiating multiple pre check requests, all request modes are returned to the browser
Access-Control-Allow-Methods: GET, POST, PUT
// The server supports pre checking the access control request headers property value in the request header information
Access-Control-Allow-Headers: X-Custom-Header
// The server allows the browser to send cookie s
Access-Control-Allow-Credentials: true
// The validity period of the specified pre inspection request is 20 days, during which it is not necessary to send another pre inspection request again
Access-Control-Max-Age:1728000
Content-Type: text/html; charset=utf-8
Keep-Alive: timeout=2, max=100
// Long connection
Connection: Keep-Alive
Content-Type: text/plain

Then the browser will send a CORS request like a simple request. The request header must contain the Origin attribute, and the server's response header must also contain the access control allow Origin attribute.  

3. Agency mode

The cross domain restriction is caused by the browser's homology policy. Using nginx as the HTTP interface for accessing other services does not need to execute JS. There is no homology policy restriction, so you can use nginx to create a proxy server. The domain name of this proxy server is consistent with the domain name to be accessed by the browser, Then modify the domain name in the cookie to the domain name of the HTTP interface to be accessed through the proxy server, and realize cross domain through reverse proxy.
Configuration information of Nginx:

server {
    # Port of proxy server
    listen 88;
    # Domain name of proxy server
    server_name http://127.0.0.1;
    location / {
        # Domain name + port of reverse proxy server
        proxy_pass http://127.0.0.2:89;
        # Modify the domain name in the cookie
        proxy_cookie_domain http://127.0.0.2 http://127.0.0.1;
        index index.html index.htm;
        # Set the current proxy server to allow browsers to cross domains
        add_header Access-Control-Allow-Origin http://127.0.0.1;
        # Set the current proxy server to allow the browser to send cookie s
        add_header Access-Control-Allow-Credentials true;
    }
}

Front end code:

var xhr = new XMLHttpRequest();
// Set browser to allow sending cookie s
xhr.withCredentials = true;
// Accessing nginx proxy server
xhr.open('get', 'http://127.0.0.1:88', true);
xhr.send();

Keywords: computer

Added by web.designer.iq on Thu, 24 Feb 2022 13:09:36 +0200