javascript cross domain reasons and solution sharing

  • 2020-05-27 04:13:33
  • OfStack

Causes of cross-domain problems

The cross-domain problem is the browser same origin policy restriction, the current domain name js can only read under the same domain window properties.

Cross-domain problem generation scenarios

Cross-domain issues arise when using js on a page to retrieve data from other sites. For example, when using ajax in a web site to request weather, express, or other data interfaces from other sites, and when requesting data from hybrid app, the browser will prompt the following error. In this scenario, the cross-domain problem of js needs to be solved.

XMLHttpRequest cannot load http:// the domain name you requested. No 'Access-Control-Allow-Origin' header is on the requested resource resource Origin 'http:// the domain name 'is therefore not allowed access for the current page.

What situations can cause cross-domain problems

The url composition of a website includes the protocol name, subdomain name, main domain name, and port number. For example, https:// github.com /, where https is the protocol name, www is the subdomain name, github is the primary domain name, and github is the port number 80. When data is requested from one url in the page, if one of the protocol name, subdomain name, primary domain name and port number of this url is different, cross-domain problems will occur.
Even on the http://localhost:80/ page request http://127.0.0.1:80/ will have cross-domain issues

Solve cross-domain problems

There are 1 ways to solve cross-domain problems

Using jsonp
Server-side proxy
The server sets Access-Control-Allow-Origin in the Request Header header to specify the domain name for which the data is available

The solution of jsonp

json indicates jsonp

The principle of

The principle of jsonp to solve the cross-domain problem is that the browser's script tag is not subject to the same origin policy (you can set the script src property in your web page to ask the path of static files in the cdn server). Then you can use the script tag to get the data from the server, and when you request it, you can add a parameter of callbakc=? , & # 63; The callback method you want to execute at time.

The front-end implementation

Take the ajax method of jQuery2.1.3 as an example


$.ajax({
    url:"",
    dataType:"jsonp",
    data:{
        params:""
        }
}).done(function(data){
    //dosomething..
})

It is not enough just for the client to request data using jsonp, because jsonp's request is placed in the script tag. Unlike normal requests, it requests a piece of js code. If the server returns an json string, the browser will report an error. So the server needs to do some processing for jsonp to return the data.

The server returns data processing

As mentioned above, the principle of jsonp is to use the script tag to solve the cross-domain problem, but the script tag is used to get the js code, so how can we get the requested data?

This requires the server to make some judgments. When there is an callback attribute in the parameter, the returned type should be application/javascript, and the data should be executed as the parameter of callback. The following is an example of the format of the data returned by jsonp


/**/ typeof jQuery21307270454438403249_1428044213638 === 'function' && jQuery21307270454438403249_1428044213638({"code":1,"msg":"success","data":{"test":"test"}});

This is the implementation code of express4.12.3 about jsonp


 // jsonp
 if (typeof callback === 'string' && callback.length !== 0) {
 this.charset = 'utf-8';
 this.set('X-Content-Type-Options', 'nosniff');
 this.set('Content-Type', 'text/javascript');

 // restrict callback charset
 callback = callback.replace(/[^\[\]\w$.]/g, '');

 // replace chars not allowed in JavaScript that are in JSON
 body = body
  .replace(/\u2028/g, '\\u2028')
  .replace(/\u2029/g, '\\u2029');

 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
 // the typeof check is just to reduce client error noise
 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
 }

The server side is set to Access-Control-Allow-Origin

In this way, the server only needs to set Access-Control-Allow-Origin in the header header of response as the domain name that can request data under the current domain name. 1 can be set as in general case. This way the client does not need to use jsonp to retrieve the data.
There is a discussion on zhihu about whether there is a security problem with the setting of Access-Control-Allow-Origin.

http://www.zhihu.com/question/22992229

Browser support

Access-Control-Allow-Origin is a new standard added to html5, but it is not supported below IE10, so if the product is for PC, you should use the server proxy or jsonp.

That's all for this article, and I hope it will be helpful for you to learn javascript cross-domain.


Related articles: