With the help of node practices for cross-origin instances of JSONP, node practices for jsonp

Source: Internet
Author: User
Tags node server

With the help of node practices for cross-origin instances of JSONP, node practices for jsonp

I. Preface:

Browser security is based on the same-source policy. The so-called same-source policy is three-phase same:

1. The protocol is the same;

2. The domain name is the same;

3. the ports are the same.

However, there are advantages and disadvantages in everything. The same-origin policy also leads us to want to use AJAX cross-origin requests, but NO !! To avoid this restriction, one method is JSONP.

The basic idea of JSONP is to request data from the server through the src of <script>, and this is not restricted by the same-source policy (the same is true for src of img and iframe ); the server then puts the corresponding data into the specified function callback name and returns it to the front-end.

This enables cross-origin request information.

As shown in:

 

After learning about the general idea of JSONP, let's use node to build a simple server and implement the cross-origin request journey brought by JSONP step by step with the frontend.

2. Build a node server:

Because the frontend must implement cross-origin requests, it must work with the background. Here, we use node to simulate backend servers.

So, you have to have a certain understanding of node and the development environment.

Next, let's write a simple node server.

First, we need to introduce the http module because it is based on http requests. Then create an http server, for example, listening for port 8080.

As follows:

'Use strict '; // use require to include the http library in the program var http = require ('http'); // create a new http server var server = HTTP. createServer (); // responds to the request server through the request event. on ('request', function (req, res) {res. writeHead (200, {'content-type': 'text/html; charset = UTF-8 '}); res. end ('hell World \ n') ;}); // listens to port 8080 server. listen ('20140901'); // It is used to prompt that the server is successfully started. log ('server running! ');

Next, because we need to distinguish the requests using JSONP from normal requests, we have to judge and process them in the background-by parsing the url string, assume that we use the path with '/jsonp.

As follows:

'Use strict '; // use require to include the http library in the program var http = require ('http '); // introduce the url module to parse the url string var url = require ('url'); // create a new HTTP server var server = http. createServer (); // responds to the request server through the request event. on ('request', function (req, res) {var urlPath = url. parse (req. url ). pathname; // if urlPath is 'jsonp', it is deemed that the request is an http request carrying the jsonp method if (urlPath = '/jsonp') {res. writeHead (200, {'content-type': 'application/json; charset = UTF-8 '}); va R data = {"name": "Monkey"}; data = JSON. stringify (data); // assume that the defined callback function is named test var callback = 'test' + '(' + data + ');'; res. end (callback);} else {res. writeHead (200, {'content-type': 'text/html; charset = UTF-8 '}); res. end ('hell World \ n') ;}}); // listens to port 8080 server. listen ('20140901'); // It is used to prompt that the server is successfully started. log ('server running! ');

In the 19 lines in the above Code, the disadvantage is that we have left the callback function name dead. When we determine that the request is JSONP, we can only pass test to the front end. This is obviously unreasonable.

Therefore, we need to use the querystring module to process the query string.

As follows:

'Use strict '; // use require to include the http library in the program var http = require ('http '); // introduce the url module to parse the url string var url = require ('url'); // introduce the querystring module to process the query string var querystring = require ('querystring '); // create a new HTTP server var server = http. createServer (); // responds to the request server through the request event. on ('request', function (req, res) {var urlPath = url. parse (req. url ). pathname; var qs = querystring. parse (req. url. split ('? ') [1]); if (urlPath ='/jsonp' & qs. callback) {res. writeHead (200, {'content-type': 'application/json; charset = UTF-8 '}); var data = {"name": "Monkey"}; data = JSON. stringify (data); var callback = qs. callback + '(' + data + ');'; res. end (callback);} else {res. writeHead (200, {'content-type': 'text/html; charset = UTF-8 '}); res. end ('hell World \ n') ;}}); // listens to port 8080 server. listen ('20140901'); // It is used to prompt that the server is successfully started. lo G ('server running! ');

In this way, we can build a server we need.

The server has a cross-origin request.

Iii. JSONP cross-origin request tour:

Because we implement the request by using the src in the <script> label, we have agreed in the server to add '/jsonp? Callback', it is considered as a JSONP request, and callback is carried into an existing global method in js.

Therefore, the code can be as follows:

<!DOCTYPE html>  

Okay. The front and back ends are all encoded. Next, let's take a look at the effect.

Start the node server first, as shown below:

Note: I put the server. js we set up in D:/JSONP.

Next, run the html code written above to find that the request is successful and execute the test method.

 

However, when we come in, we have to request cross-origin requests. Is it a bit inappropriate? So we can dynamically create script elements and specify the corresponding requests so that we can do what we want.

As follows:

// Dynamically create a script tag and request function addscriptTag (src) {var script = document. createElement ('script'); script. setAttribute ('type', 'text/javascript '); script. src = src; document. body. appendChild (script) ;}; // For example, after onload, the cross-origin request window. onload = function () {addscriptTag ('HTTP: // 127.0.0.1: 8080/jsonp? Callback = monkey') ;}; // callback method, which must be a global method; otherwise, the function monkey (data) {alert (data );};

JSONP also needs to note that the method of the callback function must be global. Otherwise, an error will be reported because the request is sent through the src request of the script and is executed immediately after the request is successful.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.