Cross-domain problems and solutions that front-end programmers must know

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

foreword

Cross-domain problems and solutions that front-end programmers must know

node agent

principle

The same-origin policy occurs in the browser and not in the server. Through a nodecode that can cross domains, it helps the front-end to request data from other back-ends (that is, write a back-end to send requests to other back-ends). The diagram is as follows:

Code

The two machines are connected to the same LAN, their own front end:

   var ajax = new XMLHttpRequest()
            ajax.open('get', 'http://localhost:3001')
            ajax.send()
            ajax.onreadystatechange = () => {
                if (ajax.readyState == 4 && ajax.status == 200) {
                    console.log(ajax.responseText);
                }
            }

own backend:

const http = require('http');
// const urllib = require('url');
http.createServer(function (req, res) {

    res.writeHead(200, {
        "Access-Control-Allow-Origin": 'http://127.0.0.1:5500',//只允许自己前端请求
    })
    http.request({
        host: '别人的ip地址',
        port: '别人后端运行的端口号',
        method: 'GET',
    }, result => {
        result.on('data', function (msg) {
            console.log(msg.toString());
            //拿到数据返回给自己的前端
            res.end(msg.toString())
        })
    }).end()

    // res.end(JSON.stringify({ msg: 'hello world' }))

}).listen(3001, () => {
    console.log('listening on port 3001');
});

Nginx

principle

Its implementation principle  node is the same as that of the agent, except that  node the agent sends requests to other people's backends through the backend written by itself, Nginx but it a piece of software that only needs configuration files when using it.

Introduction

Nginx is an open source lightweight  Web server, reverse proxy server, load balancer and  HTTP cache. It is characterized by high concurrency, high performance and low memory. It is specially developed for performance optimization, performance is its most important consideration, and the implementation pays great attention to efficiency.

Nginx configuration file

Nginx The configuration file consists of three parts:

...              //全局块

events {         //events块
   ...
}

http      //http块
{
    ...   //http全局块
    server        //server块
    { 
        ...       //server全局块
        location [PATTERN]   //location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     //http全局块
}

The first part of the global block

It mainly sets some  Nginx configuration instructions that affect the overall operation of the server. For example:  worker_processes 1worker_processes The larger the value, the more concurrent processing can be supported.

second part  eventsblock

events The instructions involved in the block mainly affect  Nginx the network connection between the server and the user. For example:  worker_connections 1024; The maximum number of connections supported.

third part  httpblock

http Blocks include  http global blocks and  server blocks, which are the most frequent part of server configuration, including most functions such as configuring agents, caching, and log definitions.

serverBlock: Configure the relevant parameters of the virtual host.

locationBlock: configure request routing, and the processing of various pages.

Using NGINX as a Node.js proxy

Create a proxy server block: In the configuration file, you need to create a new server block to define Node.jsthe proxy. Look at the code below:

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://localhost:3000;  //将代理请求转发至Node.js应用的地址和端口
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

In the above sample code, your-domain.comit should be replaced with your domain name or server IPaddress. proxy_passDirectives are used to forward requests to Node.jsthe application's address and port. Here it is assumed that Node.jsthe application is running on the local port 3000, you need to modify it according to the actual situation.

The above two and the two mentioned in the previous article are the most common and widely used methods for dealing with cross-domain. Then we will talk about the uncommon ones in some cases. The method that can only be used below.

postMessage

There is an older tag <iframe></iframe>that can be used to nest subpages in a page. postMessageThe method windowabove can be used here; when iframenested subpages are used in the page, and the source of the parent and child pages is different, postMessagecommunication can be achieved.

Look directly at the code:

<!-- 父页面 -->

<body>
    <h1>这是首页</h1>

    <iframe id="another" src="http://127.0.0.1:63251" frameborder="4" width="500" height="400"></iframe>

    <script>
        document.getElementById('another').onload = function () {
            // console.log(this.contentWindow);

            this.contentWindow.postMessage({ name: 'song', age: 18 }, 'http://127.0.0.1:63251')
            window.onmessage = function (e) {
                console.log(e.data);
            }
        }
    </script>
</body>
<!-- 子页面 -->

<body>
    <h3>another page</h3>

    <script>
        window.onmessage = function (e) {
            console.log(e.data, '-----');
            e.source.postMessage(`${e.data.name}今年${e.data.age}`, e.origin)
        }
    </script>
</body>

domain

This method is postMessagethe same as the method, and it is also used to <iframe></iframe>solve the cross-domain on the label; only need to declare the parent-child page document.domain='xxx'to tell the browser that there is no need to cross-domain.

code show as below:

<!-- 父页面 -->

<body>
    <h1>这是home 页面</h1>
    <iframe id="about" src="http://127.0.0.1:50250/" frameborder="1"></iframe>

    <script>
        document.domain = '127.0.0.1'//告诉浏览器域名一样,只要域名一样就能通信
        document.getElementById('about').onload = function () {
            console.log(this.contentWindow.data);//获取到子页面的数据
        }
    </script>
</body>
<!-- 子页面 -->

<body>
    <h3>about page</h3>
    <script>
        document.domain = '127.0.0.1'
        var data = '这是about页面的数据'
    </script>
</body>

WebSocket

what is it

WebSocketIs a Webprotocol that enables full-duplex communication within an application. It allows persistent connections between servers and clients, enabling real-time data transfer and instant communication. SocketThe protocol is not affected by the same-origin policy and can cross domains.

General Workflow

  1. Handshake ( Handshaking): Before establishing WebSocketa connection, an initial HTTPhandshake is performed between the client and the server. The client sends a HTTPrequest containing specific header information to the server, and the server verifies the request and returns specific header information in the response, indicating that the handshake is successful.
  2. Connection establishment: Once the handshake is successful, WebSocketthe connection is established, and real-time two-way communication can take place between the server and the client.
  3. Data transmission: WebSocketAfter the connection is established, the server and the client can communicate in real time by sending messages. Servers and clients can send messages to each other at any time without going through the traditional HTTPrequest-response model.
  4. Connection close: When the communication ends or the connection needs to be closed, the server or client can send a specific close frame to indicate that the WebSocketconnection is closed.

code demo

front end:

<body>
    <script>
        function myWebScoket(url, params) {
            return new Promise(function (resolve, reject) {
                const scoket = new WebSocket(url) // 对这个url建立scoket连接
                scoket.onopen = () => { // 向后端发送数据
                    scoket.send(JSON.stringify(params))
                }
                // 接受响应
                scoket.onmessage = (res) => {
                    resolve(res.data)
                }
            })
        }

        myWebScoket('ws://localhost:3000', { name: 'song', age: 20 })
            .then(data => {
                console.log(data);
            })
    </script>
</body>

rear end:

const WebSocket = require('ws');

const ws = new WebSocket.Server({ port: 3000 })

ws.on('connection', (obj) => { // 前端跟我建立了连接
    obj.on('message', (msg) => { // 前端给我传递了数据
        console.log(msg.toString());
        const data = JSON.parse(msg.toString());
        let age = data.age
        setInterval(() => {
            console.log(age);
            obj.send(`${data.name} 今年 ${age++} 岁了`);
        }, 2000)//每隔两秒打印一次

    })
})

summary

For cross-domain problems and solutions, we described these two articles in detail, which are probably these 7 methods to solve cross-domain. There may be omissions or errors in the article, and you are welcome to point them out.

 

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/131321069