Ajax Cross-Domain solutions

Source: Internet
Author: User
Tags script tag

Using AJAX, if the request back-end address and page access address "URL header" is different, there will be access denied, which requires cross-domain to address the front-end communication problems

Method One: Set the Google Chrome properties to allow cross-domain

Copy a Google browser icon, right----Property-----shortcut tab------Append-disable-web-security to the target----Click Apply-----Click OK

Method Two (Recommended): Server reverse proxy resolves cross-domain

Handling for large applications

Refers to a proxy server that accepts connection requests on the Internet, then forwards the request to a server on the internal network and returns the results from the server to the client requesting a connection on the Internet, where the proxy server appears as a reverse proxy server externally. Here the Nginx and node are implemented as follows:

 1  //  File nginx.conf Add code  2  3  location ~/API {4  //  Address of the request backend  5  proxy_pass http:// www.b.com:8080;  6 } 
 1  //  The proxy for node is as follows  2  3  proxytable: { 4  '/api '  5  target: ' http://www.b.com:8080/'  6  changeorigin: true   7  // pathrewrite: {' ^/api ': '/'} override  8  }  9 }, 

Description: If the page URL is http://www.a.com, the page requires Ajax to request the address of the backend http://www.b.com:8080/api/dothis.do. If the reverse proxy is set, the data can be obtained through http://www.a.com/api/dothis.do, which solves the cross-domain problem without exposing the backend address to the user.

Method Three (CORS cross-domain ): Back end through access-control-allow-origin to solve

Suitable for small or personal applications with high credit

CORS is a cross-domain scenario that is proposed after ES5. Only need to configure a cross-domain response header interface on the server

Access-control-allow-origin is a policy defined in HTML5 that addresses the cross-domain of resources. He is returning the response header with the Access-control-allow-origin identity through the server to resolve cross-domain permissions issues for the resource.

If you promise access to all domain names, you can set Access-control-allow-origin in the header: *.

If you promise some domain name access, here will be PHP as an example to achieve the following, here will only promise the front-end URL for http://www.a.com to access:

1 $origin = isset ($_server[' Http_origin ')? $_server[' http_origin ': '; 2         $allow _origin = Array (3             ' http://www.a.com ',4        ); 5         if (In_array ($origin, $allow _origin)) {6             header (' Access-control-allow-origin: '. $ Origin); 7         }

Method Four: Jsonp resolve the cross-domain of GET requests

JSON is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access through JavaScript callback. Its limitations are mainly to support only get

The realization of the idea is:
The server-side assembles the client's pre-set JSON data, which is passed back to the client via callback.

Here, for example, PHP returns the following:

1 <? PHP 2    $data = Array (); // data that needs to be returned 3    $callback = $_get[' callback '); 4    echo $callback. ' ('. Json_encode ($data). ') ' ; 5    exit; 6 ?>

The front end is an example of jquery's Ajax request, which encapsulates the implementation of the JSONP

1 $.ajax ({2     type: "Get"// if 3     URL: "www.b.com:8080", 4     DataType: "Jsonp",5     JSONP: "Callback",// passed to the request handler or page, The parameter name used to obtain the JSONP callback function name 6     success:function(JSON) {},7     Error:function() {}8 });

Online to find a native JS implementation, the code is as follows:

1 functionAjax (params) {2params = Params | | {}; 3Params.data = Params.data | | {}; 4  varJSON = PARAMS.JSONP?Jsonp (params): JSON (params); 5  //JSONP Request6  functionJsonp (params) {7   //create a script tag and add it to the page8   varCallbackname =Params.jsonp; 9   varHead = document.getElementsByTagName (' head ') [0]; Ten   //sets the name of the callback parameter passed to the background OneParams.data[' callback '] =Callbackname;  A   vardata =Formatparams (Params.data);  -   varScript = document.createelement (' script ');  - head.appendchild (script);  the   //To Create a JSONP callback function -Window[callbackname] =function(JSON) { - head.removechild (script);  - cleartimeout (Script.timer);  +Window[callbackname] =NULL;  -Params.success &&params.success (JSON);  +   };  A     //Send Request atSCRIPT.SRC = Params.url + '? ' +data;  -   //set timeout processing in order to know if the request was successful -   if(params.time) { -Script.timer = SetTimeout (function() {   -Window[callbackname] =NULL;  - head.removechild (script);  inParams.error &&Params.error ({ -Message: ' Timeout ' to     });  + }, time);  -   }   the  };  *  //Formatting Parameters $  functionformatparams (data) {Panax Notoginseng   vararr = [];  -    for(varNameinchdata) {   theArr.push (encodeURIComponent (name) + ' = ' +encodeURIComponent (Data[name]));  +   };  A   //add a random number to prevent caching theArr.push (' v= ' +random ());  +   returnArr.join (' & '));  -  }   $  //get random number $  functionrandom () { -   returnMath.floor (Math.random () * 10000 + 500);  -  } the}

Benefits of Cors compared to JSONP:

1. JSONP can only implement get requests, and Cors supports all types of HTTP requests.

2, using cors, developers can use ordinary XMLHttpRequest to initiate requests and obtain data, than JSONP have better error handling.

3. JSONP is primarily supported by older browsers, which often do not support cors, and most modern browsers already support Cors.

Ajax Cross-Domain solutions

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.