Cross-domain (a type of request scenario restricted by browser same-origin policy)

define

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain

The same origin policy restricts the following behaviors:

Cookie, LocalStorage, and IndexDB cannot be read. DOM and Js objects cannot be obtained. AJAX requests cannot be sentCopy the code

Solutions:

1. Through JSONP(JSONP disadvantage: only get one request)

The following example uses a script tag plus a callback function

Can be found in

    <script>
        function f(data){
    		alert(data)
    	}
    </script>
    <script src="http://localhost:8000? callback=f"></script>
Copy the code
    var app2 = express();
    app2.get("/".function(req,res){
    	var funcname = req.query.callback;
        res.send(funcname+"('messgae')")
    })
    app2.listen(8000)
Copy the code

2. Cross-domain Resource Sharing (CORS)

Browsers classify CORS requests into two categories: Simple request and not-so-simple Request.

A simple request

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

(1) Request method is one of the following three methods:

  • HEAD
  • GET
  • POST

(2) HTTP headers do not exceed the following fields:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-type: is limited to three values
    • Application/X-www-form-urlencoded, in the default encType, form form data is coded as key/value format and sent to the server (form default submit data format)
    • Multipart /form-data. This format is used when files need to be uploaded in the form
    • Text /plain The format is plain text

For simple requests, the browser issues CORS requests directly. Specifically, add an Origin field to the header information.

The Origin field indicates the source (protocol + domain name + port) from which the request is sent. Based on this value, the server decides whether to approve the request or not.

If Origin specifies a domain name within the license, the server returns a response with several additional header fields.

// This field is required. Its value is either the value of the Origin field at the time of the request, or an *, indicating acceptance of requests for any domain name. Access-Control-Allow-Origin: http://api.bob.com Access-Control-Allow-Credentials: true Access-Control-Expose-Headers: FooBar Content-Type: text/html; charset=utf-8Copy the code

CORS requests do not send cookies and HTTP authentication information by default. To send cookies to the server, specify the access-Control-allow-credentials field with the server’s permission.

Access-Control-Allow-Credentials: true
Copy the code

On the other hand, the developer must turn on the withCredentials attribute in the AJAX request.

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
Copy the code

Here is an example of a modification

    // Modify the response header directly on the express backend!!
    var app2 = express();
    app2.get("/".function(req,res){
    	res.header("Access-Control-Allow-Origin"."*")
    	res.send("message")
    })
    app2.listen(8000)
Copy the code

Non-simple request

Non-simple requests are requests that have special requirements on the server, such as the request method being PUT or DELETE, or the content-Type field being of Type Application/JSON.

CORS requests that are not simple requests are preceded by an HTTP query request, called a “preflight” request.

The browser asks the server if the domain name of the current web page is on the server’s license list, and what HTTP verb and header fields can be used. The browser issues a formal XMLHttpRequest request only if it receives a positive response; otherwise, an error is reported.

CORS serves the same purpose as JSONP, but is more powerful than JSONP.

Recommended videos:

www.bilibili.com/video/BV1Kt…

References:

Ruan Yifeng cross-domain resource sharing CORS details

Other cross-domain solutions:

  • Document.domain + iframe cross domain
  • location.hash + iframe
  • Window. name + iframe cross domain
  • PostMessage cross-domain
  • Nginx agents cross domains
  • Nodejs middleware proxies cross domains
  • The WebSocket protocol is cross-domain

See article: segmentfault.com/a/119000001…

And again late

Other Reading learning [Ajax, Fetch, Axios]

ajax

    $.ajax({
      url: "test.html".context: document.body
    }).done(function() {$(this ).addClass( "done" );
    });
Copy the code

Article recommendation:

Api.jquery.com/jquery.ajax…

fetch

    // Use the case submit form
    const form = document.querySelector('form');
    
    const response = await fetch('/users', {
      method: 'POST'.body: new FormData(form)
    })
Copy the code

Article recommendation:

Ruan Yifeng Fetch API tutorial

axios

    // Send a POST request
    axios({
      method: 'post'.url: '/user/12345'.headers: {'content-type':"application/x-www-form-urlencoded"},data: {
        firstName: 'Fred'.lastName: 'Flintstone'
      }
    }).then(res= >{console.log(res.data)});
Copy the code

Article recommendation:

Instructions for UseAxiosEnglish description

axiosChinese website

Recommended videos:

www.bilibili.com/video/BV14t…