And the cross-domain separated front and rear ends

Baidu article about cross-domain almost every article will have such a map, and these solutions

image.png

As long as the current page where the url with different requests are all cross-domain request, or why I can access cdn introduced js or css or images from other sites, it is because srcof this label is to support cross-domain, you get to go outside the network using ajax the js, css, try out, so == on the page with the address of a server request which is strongest solve cross-domain solutions ==

Coming from jq-ajax article can go back, content Chaogang the following

vue-cli is to start a development version of the local server, the domain name is localhost: port, naturally not in the write request in scaffolding, it can only finish packing out into the packed files with requests for the same domain name server in slightly, although this may be, but too silly, change it packaged released it, or look at other solutions to cross-domain right

To solve cross-domain solutions

  1. By jsonp cross-domain (cross-domain can only get request)
  2. document.domain + iframe cross-domain
  3. location.hash + iframe
  4. window.name + iframe cross-domain
  5. Cross-domain postMessage
  6. Cross-Origin Resource Sharing (CORS)
  7. nginx proxy cross-domain
  8. nodejs middleware agent across domains
  9. WebSocket protocol across domains

The above program we just take the sixth spot, the first 7:00, the eighth point, [7 and 8 are the same]

Look back axios articles inside this code

baseURL: process.env.NODE_ENV === 'development' ? '/proxy' : 'http://xxx.com',

The need to solve the problem

  • The official version of online cross-domain transfer fails
  • Local development cross-domain transfer fails

The official version of online cross-domain transfer fails
first is to support cross-domain server, called CORS, that you want to set up the back-end, if it is java and nodejs development, see notes have code that can be copied, open the CORSrear http://xxx.comto support the cross-domain , that is, after you complete package on http://aaa.comrequest http://xxx.comfor all requests it

Local development cross-domain transfer fails
since the lines are open CORS, and can also open local CORS, then the above code change

baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:后端的本地端口' : 'http://xxx.com',

Okay, not individual test, in fact, it should be possible, but do not know why, they still use the above method it
since cross-domain browser can not let you go after the local server is transferred to the request, that is, let localhost: port the request to the server, the above /proxyis abbreviated, actually localhost:端口/proxy, you can understand it, why do you want to add this value, and this value is a logo, into aa, bb line, this value is to tell the scaffolding server, you If you see a request with this logo, you will go to another address for me to take over the requested data

The question is how to make my server has this feature, vue-cli comes to have a proxy plug-in, configure it on the line
in vue.config.js in

devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // 这个就是被监听的标识
      "/proxy": {
        // 然后脚手架去这个地址请求数据,这个就是本地的后端服务器以及端口
        target: "http://127.0.0.1:8080/",
        changeOrigin: true,
        pathRewrite: { '^/proxy': '' },
     }
   }
}

After many proxy configuration, this is the most basic writing, if there are other needs, you can check Baidu

Then local scaffolding should be able to transfer through the local interface, and the line item can be transferred through the interface line, the issues are resolved, is a baseURL ternary operator and a few lines of proxy configurations only, I should not have to write so many of the self-understanding of the code on the line, but still would like to explain a explanation written two notes out

Before and after the end of the separation talk about
this is a coming face questions

Front and rear end are not isolated
features are: full page template generation after the back-end, back-end data by the rendering
such as node template rendering of ejs
such as java and jsp jstl of rendering
these require special wording to learn, not a normal html tags, are now eliminated because very few people understand, particularly high maintenance costs

Front and rear end of the semi-detached
is to put the project on the same server with a server, the very common very common development model, jq era

Before and after the end of the separation
is the front-end code for a server, a server back-end code, open cross-domain support, develop their own complete update their own code on the line, but the separation of the front and rear end lost the same origin policy, the absence of the same origin policy, the browser is vulnerable to XSS, CSFR attacks, you can view classless "security and attack" notes

Supplementary jsonp
face questions come forward, but normally will not use, before watercress and Baidu's search interface is implemented by jsonp
jsonp is how to achieve, the principle is that you put a global == == method name as a parameter passed to the back end , such parameters called cb, to the rear end of the interface parameters, then check the database in the parameter packet, the return value is as follows, and the return value is set to js format, automatically executed after the global data return method cb, this parametric approach is that cross-domain data

cb('{"name":"name"}')

jq use jsonp

$.ajax({
    type : "get",
    url : "http://xxxx",
    dataType: "jsonp",
    jsonp:"callback",
    jsonpCallback: "doo",
    success : function(data) {
        console.log(data);
    }
});

fetch and axios no jsonp, needs its own package

(function (window,document) {
    "use strict";
    var jsonp = function (url,data,callback) {

        // 1.将传入的data数据转化为url字符串形式
        // {id:1,name:'jack'} => id=1&name=jack
        var dataString = url.indexof('?') == -1? '?': '&';
        for(var key in data){
            dataString += key + '=' + data[key] + '&';
        };

        // 2 处理url中的回调函数
        // cbFuncName回调函数的名字 :my_json_cb_名字的前缀 + 随机数(把小数点去掉)
        var cbFuncName = 'my_json_cb_' + Math.random().toString().replace('.','');
        dataString += 'callback=' + cbFuncName;

        // 3.创建一个script标签并插入到页面中
        var scriptEle = document.createElement('script');
        scriptEle.src = url + dataString;

        // 4.挂载回调函数
        window[cbFuncName] = function (data) {
            callback(data);
            // 处理完回调函数的数据之后,删除jsonp的script标签
            document.body.removeChild(scriptEle);
        }

        document.body.appendChild(scriptEle);
    }

    window.$jsonp = jsonp;

})(window,document)

Supplement the WebSocket
the WebSocket is a two-way communication protocol, which is the principle chat qq, micro letter, after the connection is established, WebSocket server and the client can take the initiative to send or receive data to each other without restriction-origin policy.

function WebSocketTest(){
    if ("WebSocket" in window){
        alert("您的浏览器支持 WebSocket!");
        // 打开一个 web socket
        var ws = new WebSocket("ws://localhost:3000/abcd");
        ws.onopen = function(){
            // Web Socket 已连接上,使用 send() 方法发送数据
            ws.send("发送数据");
            alert("数据发送中...");
        };
        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            alert("数据已接收...");
        };
        ws.onclose = function(){
            // 关闭 websocket
            alert("连接已关闭...");
        };
    } else{
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
    }
}

Guess you like

Origin www.cnblogs.com/pengdt/p/12046420.html