JS Cross-domain Reasons and Solutions

Causes of cross-domain issues

The cross-domain problem is the limitation of the browser's same-origin policy. The js of the current domain name can only read the window properties under the same domain.

Scenarios arising from cross-domain problems

When you want to use js in the page to obtain data from other websites, cross-domain problems will arise. For example, when using ajax in the website to request the weather, express delivery or other data interfaces of other websites, and requesting data in the hybrid app, the browser will The following error will be prompted. In this scenario, it is necessary to solve the cross-domain problem of js.

XMLHttpRequest cannot load http://你请求的域名. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://当前页的域名' is therefore not allowed access.

What situations can create 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 main domain name, and the port number is 80. When requesting data from a url in the page, if the protocol name of the url, If any one of the subdomain name, main domain name, and port number is different, cross-domain problems will arise.
Even on http://localhost:80/page requests http://127.0.0.1:80/there will be cross-domain issues

Solve cross-domain problems

There is one way to solve cross-domain problems

  • use jsonp
  • server proxy
  • The server sets the domain name in the Request Headerheader Access-Control-Allow-Originto specify the data that can be obtained

jsonp solution

json≠jsonp

principle

The principle that jsonp solves the cross-domain problem is that the browser's scripttags are not restricted by the same-origin policy (you can ask the path of static files in the cdn server by setting scriptthe properties in your web page). srcThen you can use the script tag to get data from the server, and add a parameter to the callbakc=?, the callback method you want to execute when 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 for the client to use jsonp to request data, because the jsonp request is placed in scriptthe label. The difference from the ordinary request is that it requests a piece of js code. If the server returns a json string, then The browser will report an error. So the data returned by jsonp requires some processing on the server side.

Server returns data processing

As mentioned above, the principle of jsonp is to use scripttags to solve cross-domain, but scripttags are used to obtain js code, so how do we obtain the requested data?

This requires the server to make some judgments. When there is a callback attribute in the parameter, the returned type must be application/javascript, and the data is executed as the callback parameter. Below 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 + ');';
  }

Server settings Access-Control-Allow-Origin

In this way, as long as the server sets the header header of the response Access-Control-Allow-Originto specify the domain name that can request data under the current domain name. In general, it can be set. This way the client doesn't need to use jsonp to get the data.
There is a discussion on Access-Control-Allow-OriginZhihu as to
whether there will be security problems in setting it.

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

Browser support

Access-Control-Allow-Origin is a new standard of html5, which is not supported under IE10, so if the product is for PC, it is necessary to use server proxy or jsonp.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326570551&siteId=291194637