Cross-domain JSONP common problem solution

Due

Speaking today between the source ... to pour tea, overheard companies interviewer ask the interviewer how to fix the front cross-domain. My heart silently thought for a moment, Papa Pa instantly came up with a few key words, iframe, cors, the same origin policy, jsonp ... then I thought, although it is very common interview questions, but I am in the process of developing really have not used this way ... even jsonp principles also said that bad. Cold sweat,?, And quickly find relevant information.

Same Origin Policy

For the same-origin policy, here I will not burden describe, in simple terms, if the following three: the same protocol , the same domain name , the same port whenever there is a not met, the browser will No 'Access-Control-Allow-Origin' header is present on the requested resourcethrow your face.

solution

It can be said inevitably cross-domain issues in terms of front-end, but the same-origin policy, after all, played a significant role in the protection of network and information security. Imagine if there is no same-origin policy, other pages can easily steal your cookie, and if your cookie in your personal information ... there is horrible, but having said that cross-domain origin policy issues are also brought headache, but fortunately now there are many ways to solve.

  1. CORS cross-domain resource sharing strategy (

  2. JSONP

  3. window.name

  4. the document.domain (available under the same circumstances the primary domain)

  5. postMessage (h5 newly introduced)

  6. websocket (h5 newly introduced, from the same origin policy restrictions, so that's a good thing ... h5?)

  7. ...

Due to limited space (well ... in fact, I can not write so much), here for other ways to solve not one by one Xiangjie.

Is the Lord comes, JSONP

JSONPIt is JSON with Paddingshort, is a more common way to solve cross-domain access. Let's look at some sample code:

ajax({//此ajax方法是封装了XMLHttpRequest对象实现,具体代码与本文无关就不贴了
  method : 'get',
  url : 'http://127.0.0.1:8787',
  data : {
  'name' : '小明',//此ajax方法会自动将数据以get方式提交
  'age' : 22
  },
  success : function (message) {
    alert(message);
  },
  async : true
})

The above code is very simple, browser initiates an asynchronous ajax requests, let us look at server code:

app.get('*', function(req, res) {//这里只截取了关键代码
  res.send("测试数据");
});

Clear, easy to understand ~ so, what happend?

Cross-domain error

As expected, the browser dumped all over my face ...
Ex situ battles! JSONP burst appearances -

function showJsonp(obj){
  console.log(obj.message);
}
var url = 'http://127.0.0.1:8787/?func=showJsonp'
var script = document.createElement('script');
script.setAttribute('src',url);
script.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);

Code behind - again

app.get('*', function(req, res) {
  let callback = req.query.func;
  let content = callback+"({'message':'测试数据2'})";
  res.send(content);
});

result:

jsonp solve cross-domain

Big! Won! all! Win!
It is time to analyze the wave of tactics - usually when writing code, many people may not pay attention to, src, etc. for browser script, iframe tags and other attributes, is not the same origin policy restrictions. And jsonp to good use at this point - when we initiated the request, url followed by the named funcparameter, and this parameter is required after the callback function name used.
We dynamically insert scripttags manner, using the src attribute of the script tag to initiate the request, the browser will not come to the same origin policy matter ... and backstage constructed at the request of the data long-sawed it?

showJsonp({'message':'测试数据2'})

tell me! After the code is inserted into your script tag, what will happen? !
Of course, the implementation of already defined showJsonp function ah ~
Bingo, the perfect solution to cross-domain problem ~ ~

At last

jsonp way compatibility is very good, even those antique browser, you can also solve the problem with cross-domain jsonp way, but it can also be limited, it can only use the get way to initiate a request, and for js pages between different domains call each other can do nothing.

This article is reproduced in: ape 2048➦ https://www.mk2048.com/blog/blog.php?id=hhibk12iakj

Guess you like

Origin www.cnblogs.com/jlfw/p/12545721.html