Why cross-domain

http://localhost:8080

A request must include a protocol such as HTTP, a domain name such as localhost, and port number 8080

Same-origin policy: Path of homologous means that the request of the source and target of the agreement domain port Numbers are the same, otherwise the request is homologous, homologous strategy is a strategy that browsers now support a browser in normal circumstances, it is not allowed to different sources of resources to request access to each other, the browser such restrictions, also for site safety, If there is no same-origin restriction, the cookie in the browser can be read arbitrarily, and the data of the website can be accessed each other, which is very exposing privacy and threatening website security.

Cross domain: Because of the same origin policy, we can’t get resources from different sources, so we need to cross domain to solve the same origin policy problem in the browser.

A simple browser same-origin policy example

<! DOCTYPE html PUBLIC"- / / / / W3C DTD XHTML 1.0 Transitional / / EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title> untitled document </title> </head> <body> <script> var xmlHttpRequest =new xmlHttpRequest (); xmlHttpRequest.onreadystatechange=function() {if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){
            console.log(xmlHttpRequest.responseText);
        }
    }
    xmlHttpRequest.open("get"."http://localhost:5000/list".true);
    xmlHttpRequest.send();
</script>
</body>
</html>
Copy the code

The above is a native of ajax requests, request the source path for http://localhost:63342/webpackProjectTest/index.html? _ijt = irg82949qkhqr15ov5b6b4e190, but target path port number is 5000, the port number is different, this has violated the browser’s same-origin policy, when running HTML browser console will be submitted to the following error:

This is a cross-domain request, and we need to address this browser limitation, which is implementing cross-domain.

Native JS implements JSONP across domains and principles

Service segment code: build with Node + Express, start service port 5000,

let express = require('express');
let app = new express();
app.get("/list".function(req,res) {
    console.log(req.query);
    let {callback}=req.query;
    console.log(callback)
    let data={
        "name":"sunshine"."age":23
    }
    res.send(`${callback}(${JSON.stringify(data)}) `); }); app.listen(5000,function() {
    console.log("Server started successfully!!");
})
Copy the code

Client code: Implement JSONP using native JS

<! DOCTYPE html PUBLIC"- / / / / W3C DTD XHTML 1.0 Transitional / / EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title> </head> <body> <script>function success(data){
        console.log("Get data from server:"+JSON.stringify(data));
    }
    let scriptDom=document.createElement('script');
    scriptDom.src="http://localhost:5000/list? callback=success";
    document.getElementsByTagName('body')[0].appendChild(scriptDom);
</script>
</body>
</html>
Copy the code

Browser Access Results

Get data from the server: {"name":"sunshine"."age"23} :Copy the code

Jsonp implementation principle

Resource access labels such as Script,link,img, and iframe in native JS have cross-domain functions. When these labels are used to request resources from different sources, the browser allows them by default.

Json is the use of cross-domain scipt tag function, the cross-domain resource path is written in the script SRC of the requests for cross-domain scriptDom. SRC = “http://localhost:5000/list? callback=success”; The request path defines a callback function, which is passed along with the request to the server. The server takes this parameter and returns a call string. The browser takes the string and executes it as JS code, completing cross-domain execution.

Jsonp requires collaboration between the client and the server, with the client defining the global callback function and adding the corresponding callback function to the request parameters.

The server needs to get the callback function, put the service data in the callback function, and return it as a string.

Note: The browser has the ability to automatically parse the string returned by the server

Jquery implements JSONP across domains

The server Settings have not changed. Now the client uses jquery ajax to implement JSONP requests.

<script>
    $.ajax({
        url: 'http://localhost:5000/list', // Different domainstype: 'GET'// Jsonp mode only GET is a valid dataType:'jsonp'// Data type success:function(data){
            console.log("Server returns data:"+JSON.stringify(data));
        }
    })
</script>
Copy the code

The underlying principle of JSONP in jquery’s Ajax implementation is to use the inherent cross-domain of script tags and the encapsulation of the underlying callback functions.

In conclusion, jSONP is a kind of cross-domain implementation with Script tags, so JSONP can only implement get requests, because these resource tags cannot realize GET requests, which is also a major disadvantage of JSONP. The second major disadvantage of JSONP is that GET requests will cause the exposure of request resources. So JSONP is a relatively insecure way to request. This approach, once very popular, is being phased out and replaced by better cross-domain solutions. But the ideas behind jSONP implementations are worth learning for front-end developers.