Browser security is based on the same origin policy . The so-called homologous strategy is three identical:
1, the agreement is the same;
2, the same domain name;
3, the same port.
However, everything has pros and cons, and the same-origin strategy has led us to use Ajax cross-domain requests, but no!! One way to circumvent this limitation is to JSONP.
The basic idea of Jsonp is to request data to the server via SRC, <script>, and this is not subject to the same-Origin policy (IMG and iframe src); then the server puts the corresponding data into the specified function callback name, Back to the front end.
This enables cross-domain request information.
As shown in the following:
Understanding the general idea of Jsonp, next, we use node to build a simple server, with the front-end step-JSONP to achieve the cross-domain request journey.
| Second, build node server: |
Because the front end is required for cross-domain requests, it needs to be mated with the background. Here, we use node to emulate the backend server.
So , you have to have a certain understanding of node and the development environment. (See also "Preliminary Nodejs").
Next, let's write a simple node server.
First, we need to introduce an HTTP module because it is based on HTTP requests. Then it is used to create an HTTP server, such as listening to the 8080 port.
As follows:
' Use strict ';//to include the HTTP library in the program via requirevarHTTP = require (' http ');//Create a new HTTP servervarServer =http.createserver ();//respond to request requests with the request eventServer.on (' request ',function(req, res) {Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}); Res.end (' Hell world\n '); });//listening on port 8080Server.listen (' 8080 ');//used to prompt our server to start successfullyConsole.log (' Server running! ');
Then, because we want to distinguish between requests that use JSONP and normal requests, the backend has to judge processing-by parsing the URL string, assuming we're judging by the path name with '/jsonp '.
As follows:
1' Use strict ';2 //to include the HTTP library in the program via require3 varHTTP = require (' http ');4 //introducing URL modules to resolve URL strings5 varurl = require (' URL '));6 //Create a new HTTP server7 varServer =http.createserver ();8 //respond to request requests with the request event9Server.on (' request ',function(req, res) {Ten varURLPath =Url.parse (req.url). Pathname; One //if URLPath is ' Jsonp ', it is determined that the request is an HTTP request that carries the Jsonp method A if(URLPath = = = '/jsonp ')){ -Res.writehead (200,{' content-type ': ' Application/json;charset=utf-8 '}); - vardata = { the"Name": "Monkey" - }; -data =json.stringify (data); - //Suppose we define a callback function named Test + varcallback = ' Test ' + ' (' +data+ '); '; - Res.end (callback); + } A Else{ atRes.writehead, {' Content-type ': ' Text/html;charset=utf-8 '}); -Res.end (' Hell world\n '); - } - }); - //listening on port 8080 -Server.listen (' 8080 '); in //used to prompt our server to start successfully -Console.log (' Server running! ');
In the above code 19 lines , there is a drawback is that we have the name of the callback function is dead, when we judge the request is JSONP, only to the front-end to pass the test, this is obviously unreasonable.
So, we have to use the QueryString module to handle the query string.
As follows:
' Use strict ';//to include the HTTP library in the program via requirevarHTTP = require (' http ');//introducing URL modules to resolve URL stringsvarurl = require (' URL '));//introducing the QueryString module to process the query stringvarQueryString = Require (' querystring '));//Create a new HTTP servervarServer =http.createserver ();//respond to request requests with the request eventServer.on (' request ',function(req, res) {varURLPath =Url.parse (req.url). Pathname; varQS = Querystring.parse (Req.url.split ('? ') [1]); if(URLPath = = = '/jsonp ' &&qs.callback) {Res.writehead (200,{' content-type ': ' Application/json;charset=utf-8 '}); vardata = { "Name": "Monkey" }; Data=json.stringify (data); varcallback = qs.callback+ ' (' +data+ ');; Res.end (callback); } Else{Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}); Res.end (' Hell world\n '); } });//listening on port 8080Server.listen (' 8080 ');//used to prompt our server to start successfullyConsole.log (' Server running! ');
In this way, we set up a server we need.
The server has, and next, the front-end cross-domain request.
| Iii. Jsonp cross-domain request tour: |
Because we are using the <script> tag in the SRC to achieve the request, in the server has been agreed to add '/jsonp?callback ' after the request, it is identified as a JSONP request, and callback into a JS in the existing global method.
Therefore, the code can be as follows:
<!DOCTYPE HTML> <Head> <title>Jsonp</title> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> </Head> <Body> <Script> functionTest (data) {alert (data.name); }; </Script> <Scriptsrc= "Http://127.0.0.1:8080/jsonp?callback=test"></Script> </Body></HTML>
OK, the front and back end are coded, and then we'll look at the effect.
Start the node server first, as follows:
Note: I put the server server.js we built in D:/JSONP
Next, run the HTML code written above to see that the request was successful and execute the test method.
but, as soon as we come in, we have to cross-domain request, whether it is a bit inappropriate, so we can dynamically create the script element, and specify the corresponding request, let us do.
As follows:
//dynamically creates a script tag and requestsfunctionAddscripttag (src) {varScript = document.createelement (' script '); Script.setattribute (' Type ', ' Text/javascript '); SCRIPT.SRC=src; Document.body.appendChild (script);};//For example: After onload, cross-domain requestsWindow.onload =function() {Addscripttag (' Http://127.0.0.1:8080/jsonp?callback=monkey ');};//callback method, and must be a global method, or it will be an errorfunctionMonkey (data) {alert (data);};
JSONP also need to note that the method of the callback function must be global, or will be an error, because it is through the SRC request of the script, the request succeeds immediately after execution.
With node combat JSONP