First, let’s talk about the same origin policy:

The same origin policy is a basic security function of the browser that restricts access to scripts or texts from different sources. The same protocol, domain name, and port are the same. <img SRC = XXX > <link href= XXX > <script SRC = XXX >Copy the code

How to achieve cross-domain

The following are three mainstream cross-domain solutions:

1, the json

Its essence is to take advantage of script tags (SRC attributes) that are not restricted by the browser's same-origin policy. Although it is relatively simple to use, it only supports GET requests. Therefore, it is vulnerable to XSS attacks due to security problems and requires the cooperation of the front and back ends.Copy the code
<button id=" BTN "> Click </button> <script SRC = "https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" > < / script > < script > $(' # BTN). Click (function () {var frame = document.createElement('script'); frame.src = 'http://localhost:8000/list? fruit=apple&color=red&callback=eatFruit'; $('body').append(frame); }); Function eatFruit(res){alert(res.message+res.fruit+' is '+res.color); Router.get ('/list', (req, res) => {let data = {message: 'success! ', name: req.query.fruit, age: req.query.color } data = JSON.stringify(data) res.end('eatFruit(' + data + ')'); });Copy the code

2. The more commonly used scheme is CORS

Cors is a cross-domain resource sharing mechanism that uses additional HTTP headers to tell browsers to allow Web applications running on one Origin to access specified resources from different source servers.Copy the code
Var express = require('express'); var app = express(); var allowCrossDomain = function (req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:3001'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); } app.use(allowCrossDomain);Copy the code

3, the most convenient cross-domain solution nginx

Nginx is an extremely powerful Web server with the advantages of being lightweight, fast to start, and high concurrency. Use nginx's reverse proxy. Reverse proxy works because all requests must first be processed by Nginx, which acts as a proxy server and then forwards the requests to Node or Java services, thereby circumventing the same origin policy. Note: Direct requests to nginx will also report cross-domain errors.Copy the code

In addition, I have done websocket online customer service function before, to briefly say its communication: Websocket is a two-way communication protocol. After the connection is established, both the Server and client of websocket can actively send or receive data to each other. After the connection is established, the two-way communication between the client and server has nothing to do with HTTP, so it can be cross-domain.