Front-end cross-domain mode

 Same-origin policy: Protocols, port numbers, and hosts all agree to allow interaction, which is a security mechanism for browsers.

One, jsonp cross-domain

        JSONP is an unofficial cross-domain solution. Disadvantages: Only supports get, not post.

        Principle: With the help of the src in the script tag, it is not restricted by the same-origin policy.

        The data format commonly used by the client and server is JSON format. We can set the data format to json format. Since we use script (src attribute) to obtain data, script will be executed, so the server outsources a function to the real data. In the outsourcing layer, it is used as data in JSON format for transmission. After the client receives it, it can call the function to get the data.

        Grammar, jsonp consists of three parts: jsonp ( url , data (parameters), options (callback function, can be used with promise)) [can also be implemented with jq (omitted)]

//前端发送请求,给发送请求的代码绑定的事件函数:

// 绑定事件 鼠标失去焦点
input.onblur = function () {
    // 获取用户的输入值
    let username = this.value
    // 向服务器端发送请求 检测用户是否存在
    // 1. 创建script标签
    const script = document.createElement('script')
    // 2. 设置标签的src属性
    script.src = 'http://127.0.0.1:8000/checkusername'
    // 3. 将script插入到文档中 不插入到文档中浏览器是不会发送请求的
    document.body.appendChild(script)
}


//后端具体操作nodejs的server.js中

// checkusername
app.all("/checkusername", (request, response) => {
    // response.send("hello jsonp server"); //这样返回的话浏览器解析不了
    // response.send("console.log('hello jsonp-server')"); //返回的应该是一段js代码 是一个函数的调用
    // 标准的样式
    const data = {
        exist: 1,
        message: "用户名已经存在",
    };
    // 将数据转换成字符串
    let str = JSON.stringify(data);
    // 返回结果
    response.end(`handle(${str})`); //返回的响应体
    handle({"name":"汪汪队救火队长"})
});

2. Cross-Origin Resource Sharing (CORS)

        CORS (Cross-Origin Resource Sharing), cross-origin resource sharing. CORS is an official cross-domain solution. Its feature is that it does not require any special operations on the client side, and it is completely processed in the server , and it supports get and post requests.

The process is a bit like the TCP three-way handshake:

        The browser must first use the OPTIONS method to initiate a preflight request (preflight request) to know whether the server allows the cross-origin request. After the server confirms the permission, the actual HTTP request is initiated. In the return of the preflight request, the server can also notify the client whether to carry identity credentials (including Cookies and HTTP authentication related data).

3. Cross-domain WebSocket protocol

The WebSocket protocol is a new protocol of HTML5. Being able to realize full-duplex communication between the browser and the server while allowing cross-domain is a good implementation of server-side push technology. WebSocket itself does not have cross-domain problems, so we can use webSocket to communicate between non-same sources. 【learn】

Under the http protocol, the server will not actively initiate a request to the client, but will only respond.

In this state, if you want the web page to actively refresh the feedback, such as page games, which will always update the data, a common solution is to periodically send a request to the server to refresh. is occupied by bandwidth;

Solution 2, long polling. After the client initiates a request, the timeout period is set relatively long (such as 1min). After sending a request, if the server does not push new content immediately, it can still respond.

The essence of http is still a half-duplex protocol, so it is still not applicable to scenarios such as games that require a large amount of active data transmission, and the websocket protocol can solve this problem.

websocket only borrows http when establishing a connection, and then it has nothing to do with http

This article details what is websocket

Four, nginx proxy cross-domain

Principle: The same-origin policy is the security policy of the browser, not part of the HTTP protocol. The server side calls the HTTP interface only using the HTTP protocol, and there is no crossing problem.

Realization: configure the proxy server through nginx (the domain name is the same as test1, and the port is different) as a springboard, the reverse proxy accesses the test2 interface, and can modify the test information in the cookie to facilitate the writing of the current domain cookie and realize cross-domain login. In fact, it is like the principle of cross-domain development.

 Configuration:

 

5. Cross-domain during development, devServer.proxy (vue-cli proxy forwarding)

The browser prohibits cross-domain, but the server does not prohibit it. When running commands such as npm run dev locally, it actually runs a server with node , so proxyTable actually sends the request to its own server, and then forwarded by the server For the background server , it has been used as a proxy, because there will be no cross-domain problems.

We can set up a server locally, and then use the server to request the background server interface address

vuecli scaffolding, start a webpack development server, it can do proxy forwarding

Moreover, the front end and this server are of the same origin, both are port 8080, and the configuration of the webpack development server needs to be modified.

So:

1. There is no cross-domain problem between the proxy service and the front-end service due to the unification of the protocol domain name and port, and the request can be sent directly

2. Since the proxy service and the back-end service do not go through the restrictions of the same-origin policy of the browser, the request can be sent directly

In this way, we can forward the interface through the server in the middle, and solve the cross-domain problem in the development environment. It seems quite complicated. In fact, vue-cli has built this technology for us. We only need to configure it according to the requirements. .

That's it:

devServer: {
    proxy: {
      // http://c.m.163.com/nc/article/headline/T1348647853363/0-40.html
      '/api': { // 请求相对路径以/api开头的, 才会走这里的配置
        target: 'http://c.m.163.com', // 后台接口域名 我们要代理的真实的接口地址
        changeOrigin: true, // 改变请求来源(欺骗后台你的请求是从http://c.m.163.com)
        pathRewrite: {
          '^/api': '' // 因为真实路径中并没有/api这段, 所以要去掉这段才能拼接正确地址转发请求
        }
      }
    }
  }

//也就是说,客户端给代理服务器发送请求,客户端然后再向后端请求


 

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129200246