Ali P7 architect is how to solve the problem of cross-domain! Have you come across it?

Ali P7 architect is how to solve the problem of cross-domain!  Have you come across it?

Even if more and more projects are now a back-end management also tend to use before and after the end of the deployment of the isolated way to do it, in order to conform to the trend of the times, before and after the end of the separation arises a problem of cross-domain, cross-domain and put so many students before and after the end of the separation project linked together, because in fact, the cross-domain generated before and after the end of the separation is not due, then we look together, hoping to rely on that article to answer all the questions we cross-domain

A condition resulting cross-domain

  • Use xmlHttpRequest, that is, we usually say ajax request
  • Browser to do this thing
  • Different domain names, namely access to html page is under a domain name, but the target address internal js ajax request sent by the domain name is b

These three conditions are indispensable, especially in the third condition of many of the students do mobile terminal may not have heard, because the mobile terminal Shuang Shuang http requests using a variety of crazy hair a different domain, but the browser does not allow us to do so , a word to safety

Second, how to solve cross-domain problems

To solve cross-domain root of the problem is to break any of the three above-mentioned restrictions in, we look at the way one by one break

JSONP way

ajax request jsonp is the first to break the heavy restrictions on the use of XMLHttpRequest across domains, then I do not have in this way, and how do we, with a view jsonp period of jquery

$.ajax({
   type : "GET",
   url : "http://api.map.baidu.com/geocoder/v2/",
   data:"address=上海",
   dataType:"jsonp",
   jsonp:"callback",
   jsonpCallback:"showLocation",
   success : function(data){
       alert("成功");
   },
   error : function(data){
       alert("失败");
   }
});

Seemingly with the ajax requests, in fact, inside completely not the case, and jsonpCallback jsonp more options within it will translate the code on the page and the dom operating in such a way

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <script type='text/javascript'>
      // 后端返回直接执行的方法,相当于执行这个方法,由于后端把返回的数据放在方法的参数里,所以这里能拿到res。
      window.showLocation = function (res) {
        console.log(res)
        //执行ajax回调
      }
    </script>
    <script src='http://api.map.baidu.com/geocoder/v2/?address=上海&callback=showLocation' type='text/javascript'></script>
  </body>
</html>

This time, script src tag html page back to the server to access api.map.baidu.com due to script, img tag browser that is not xmlhttprequest restrictions, free to visit, this time corresponding back-end code made address parameters, according to the two sides agreed last good callback parameter and returns a json after being packaged, that is,

showLocation({
    status: 0,
    result: {
        location: {
            lng: 121.4219317908279,
            lat: 31.361653367912695
        },
        precise: 1,
        confidence: 80,
        comprehension: 99,
        level: "道路"
    }
})

The browser then direct execution of the corresponding showLocation () ... and so on, this is not the equivalent of the way we performed window.showLocation defined above and passed we need json return it, then our method in the ajax success on can get this type of return, and no cross-domain, it is not very subtle.

HEARTS

CORS is a W3C standard, stands for "Cross-Origin Resource Sharing" (Cross-origin resource sharing) CORS Detailed cross-domain resource sharing. This kind of play for "crack" out of browser limitations, said that the crack is actually the browser recognize some of the head on the release means, you need to set up more than a few heads in the response http

  • --Control-the Allow Access Origin : * indicates that allows all origin (html Page path browser) access, but not the homologous origin
  • -Control-Request-Access Method, : * indicates that allows all http request headers to access, because the browser sends a trigger are several scenarios preflight request to detect such options before sending the actual data, once before through preflight send or post get real data requests, this time we will need to follow cors settings to allow access to the corresponding method, triggering several cases, including
    1: request method is not GET / the HEAD / POST
    Content-Type POST request: 2 not application / x-www-form- urlencoded, multipart / form-data, or text / Plain
    . 3: request sets a custom header fields, etc.
  • --Control-the Allow Access Headers : * All the header are disposed may be allowed, with the use of the above-described configuration request method options Unicom detection, you may be required from the lower header defined in the scene
  • --Control-the Allow Access Credentials : this parameter to true only when it is necessary when using cross-domain cookie delivery needs to be set to true, and the need to front-end configuration uses ajax xhrField: {withCredential: true} to pass cookie when another safari and the latest version of chrome browser settings need to be released within the corresponding limit, refer to spike my course, when this parameter is set to true when the Access-Control-Allow-Origin can not be set to *, otherwise it can turn into any origin domain allows you to pass a cookie, you can adjust the front-end origin field pass what I what

If you are using nginx reverse proxy, you can configure directly on nginx reverse proxy

location /{
    proxy_pass http://backendserver;

    add_header Access-Control-Allow-Methods *;
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Headers *;

}

Law of Agency

Breaking the limits of different sources, I just let it homology can be, for example, to my static pages is http://a.com/index.html dynamic ajax request access is http://b.com/api/ ***

I only need the corresponding services deployed on different machines, then use a common entrance c.com domain name as the domain name nginx reverse proxy, server LAN service in static and dynamic services were hanging in the back by proxy ,Change setting

server{
    listen:80;
    server_name: c.com;

    #静态资源
    location /{
        proxy_pass http://localhost:8080/;
    }

    #ajax动态请求
    location /api{
        proxy_pass http://localhost:8081/;

    }

}

This will become a homologous

Written in the last

  • First: watching the thumbs up, thank you for your recognition of the author;
  • ...
  • Second: hand forward, to share knowledge, to allow more people to learn;
  • ...
  • Third: remember point concerns, updated daily! ! !
  • ...
    Ali P7 architect is how to solve the problem of cross-domain!  Have you come across it?

Guess you like

Origin blog.51cto.com/14409778/2414538