PHP share 25: cross-domain requests

Source: Internet
Author: User
Tags script tag

Question: How many cross-domain requests are there? What kinds of requests do JSONP support? Do you support post requests? Do you support get requests?

Because of the browser homology policy, any one of the protocol, domain name and port of the sending request URL is different from the current page address, which is a cross-domain. You can view the following table:

Method One: JSONP

This approach is mainly done by dynamically inserting a script tag. The browser does not have a homologous restriction on the resource reference to the script, and the resource is executed immediately after it is loaded into the page (without blocking).

<script>var _script = document.createelement ("script"); _script.type = "Text/javascript"; _script.src = "http:// Test.larvel.com/jsonp?callback=f ";d ocument.head.appendChild (_script);</script>

In real-world projects, JSONP is typically used to obtain JSON-formatted data, where the front and back ends usually contract a parameter callback, which is the function name that processes the returned data.

<!doctype html>

var query = _url.query;        Console.log (query);        var params = qs.parse (query);        Console.log (params);        var f = "";            f = params.callback;            Res.writehead ($, {"Content-type": "Text/javascript"});        Res.write (f + "({name: ' Hello World ')");        Res.end ();

Disadvantages:

1. Cannot send POST request in this way (here)

2, in addition to determine whether the JSONP request failure is not easy, most of the implementation of the framework is a combination of time-out to determine.

Method Two: Proxy agent

This method first sends the request to the background server, sending the request through the server, and then passing the result of the request to the front end.

<!doctype html>

varProxyurl = ""; if(Req.url.indexOf ('? ') >-1) {Proxyurl= Req.url.substr (Req.url.indexOf ('? ') + 1);      Console.log (Proxyurl); }      if(Req.method = = = ' GET ') {request.get (Proxyurl). pipe (RES); } Else if(Req.method = = = ' POST ') {          varPost = ';//defines a post variable for staging the request body informationReq.on (' Data ',function(Chunk) {//The data event listener function of req is added to the post variable whenever the request body is received .Post + =Chunk;            }); Req.on (' End ',function(){//After the end event is triggered, the post is parsed into the true POST request format via Querystring.parse and then returned to the client. Post =Qs.parse (POST); Request ({method:' POST ', Url:proxyurl, form:post}).        Pipe (RES);      }); }

Note that if you are acting on an HTTPS protocol request, your proxy first needs to trust the certificate (especially a custom certificate) or ignore the certificate check, otherwise your request will not succeed. A vivid example is provided in 12306.

It is also important to note that for the same request browser will usually read the data from the cache, we sometimes do not want to read from the cache, so we will add a Preventcache parameter, this time the request URL becomes: url?preventcache=12345567 ...; This is not a problem in itself, the problem is that when using some front-end framework (such as jquery) to send proxy proxy requests, the request URL is Proxy?url, and set preventcache:true, the framework does not correctly handle this parameter, the resulting request becomes proxy?url&preventcache=123456 (positive length should be proxy?url?preventcache=12356); The request sent after the backend intercept is url&preventcache= 123456, there is no such address, so you can not get the correct result.

Method Three: CORS

This is a way for modern browsers to support cross-domain resource requests.

When you use XMLHttpRequest to send a request, the browser discovers that the request does not conform to the same origin policy, and adds a request header to the request: Origin, a series of processing in the background, Accept the request to add a response header to the returned result: Access-control-allow-origin; The browser determines whether the corresponding header contains the value of Origin, and if so, we can get the response data, if not including the browser directly rejected, We can't get the response data at this point.

<!doctype html>

if (req.headers.origin) {            Res.writehead ($, {                "Content-type": "text/html; Charset=utf-8 ",                " Access-control-allow-origin ": ' http://localhost '/*,                ' access-control-allow-methods ': ' GET, POST, OPTIONS ',                ' access-control-allow-headers ': ' X-requested-with, content-type ' */            });            Res.write (' cors ');            Res.end ();        } The

If we remove the Access-control-allow-origin, the browser will dismiss the response and we will not get the data.

One thing to note is that the transparent server validation mechanism of Preflighted request enables developers to use custom headers, get or post methods, and different types of topic content. Summary such as:

1, non-GET, POST request

2. The content-type of the POST request is not a regular three: application/x-www-form-urlencoded (Form submitted using the Post method of HTTP), Multipart/form-data (Ibid., But mainly used when the form submits with the file upload, Text/plain (plain text)

3, the payload of the POST request is text/html

4. Set the custom header

The options request header will contain the following headers:Origin, Access-control-request-method, Access-control-request-headers, after sending this request, The server can set the following header to communicate with the browser to determine whether to allow this request.

Access-control-allow-origin, Access-control-allow-method, access-control-allow-headers

var xhr = new XMLHttpRequest ();      Xhr.onload = function () {        alert (xhr.responsetext);      };      Xhr.open (' POST ', ' http://localhost:8888/cors ', true);      Xhr.setrequestheader ("Content-type", "text/html");      Xhr.send ("F=json");

if (req.headers.origin) {            Res.writehead ($, {                "Content-type": "text/html; Charset=utf-8 ",                " Access-control-allow-origin ": ' http://localhost ',                ' access-control-allow-methods ': ' GET, Post,options ',                ' access-control-allow-headers ': ' X-requested-with, Content-type '/**/            });            Res.write (' cors ');            Res.end ();        }

  by setRequestHeader (' X-request-with ', null) the browser can be prevented from sending an options request.

According to my test, when using Cors to send cross-domain requests failed, the background is received the request, the background may also perform a data query operation, but the response to the head of the request, the browser blocked.

Method Four: XDR

This is a cross-domain solution provided by IE8, IE9, which only supports get-to-post requests, and is powerless for cross-domain protocols that are different, such as sending HTTPS requests under the HTTP protocol. Just look at Microsoft's own example.

<! DOCTYPE html>

The above is the cross-domain request resources I encountered in the actual project, there is a cross-domain need to pay special attention to the HTTPS protocol to send HTTPS requests, in addition to using proxy agent other than the solution, will be the browser directly block off. If any friend knows the solution, please let me know.

A complete test demo is attached at the end

<!doctype html>

<!doctype html>

Node-server

var http = require (' http '), var url = require (' URL '), var fs = require (' FS '), var qs = require (' querystring '); var request = R    Equire (' request '); Http.createserver (function (req, res) {var _url = Url.parse (Req.url);        if (_url.pathname = = = '/jsonp ') {var query = _url.query;        Console.log (query);        var params = qs.parse (query);        Console.log (params);            var f = "";            f = params.callback;        Res.writehead ($, {"Content-type": "Text/javascript"});        Res.write (f + "({name: ' Hello World ')");    Res.end ();      } else if (_url.pathname = = = '/proxy ') {var proxyurl = "";          if (req.url.indexOf ('? ') >-1) {Proxyurl = Req.url.substr (req.url.indexOf ('? ') + 1);      Console.log (Proxyurl);      } if (Req.method = = = ' GET ') {request.get (Proxyurl). pipe (RES);     } else if (Req.method = = = ' Post ') {var post = '; Defines a post variable for staging the request body Information Req.on (' Data ', function (chunk) {///through the Req Data event listener function, whenever theThe data of the requested body is accumulated into the post variable of post + = chunk;            });            Req.on (' End ', function () {//) after the end event is triggered, the post is parsed into a true POST request format by Querystring.parse and then returned to the client.            Post = Qs.parse (POST);                  Request ({method: ' POST ', Url:proxyurl, Form:post        }). pipe (RES);      }); }} else if (_url.pathname = = = '/index ') {fs.readfile ('./index.html ', function (err, data) {Res.writeh EAD, {"Content-type": "text/html;            Charset=utf-8 "});            Res.write (data);        Res.end ();    }); } else if (_url.pathname = = = '/cors ') {if (req.headers.origin) {Res.writehead ($, {"C Ontent-type ":" text/html; Charset=utf-8 "," access-control-allow-origin ": ' http://localhost ', ' Access-control-allow-meth        ODS ': ' get,post,options ', ' access-control-allow-headers ': ' X-requested-with, Content-type,aaaa '/**/    });            Res.write (' cors ');        Res.end (); }}). Listen (8888);

Reference: http://www.cnblogs.com/dojo-lzz/p/4265637.html

PHP share 25: cross-domain requests

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.