What is cross-domain?

Cross-domain means that the browser cannot execute scripts from other sites. For security reasons, the browser allows only the interface with the same origin, that is, the same origin policy of the browser. The same origin policy prevents cross-domain.

What is homology?

The same protocol, same domain name, same port must be the same.

If the protocol, domain name, or port of the requested page is different from that of the current page, the page is cross-domain.

Current page URL URL of the requested page Whether the same why
www.123.com www.123.com/do is The protocol, domain name, and port are the same
www.123.com www.123.com no Different protocols (HTTPS/HTTP)
www.123.com 123.com no Different domain names (www.123.com/123.com).
www.123.com:8080 www.123.com:9090 no Different ports (8080/9090)

Cross-domain solutions

  1. JSONP

Principle:

1. The same origin policy only restricts Ajax requests, not SCRIPT tags loading JS. Resources can be requested via the Script tag and receiver functions written in advance.

2. After receiving the request, the server obtains fn from the callback parameter and processes the original data (suppose {a:1}) into handleData({a:1}).

3. Resources in script will be executed as JS after loading, which is equivalent to executing handleData({a:1}), and data can be processed in the pre-defined handleData function

Code: Server-side:

const http = require('http')
const url = require('url')

http.createServer((req, res) = >{
  let urlObj = url.parse(req.url, true)
  if(urlObj.pathname === '/getWeather') {let data = {city:'hangzhou'.weather:'sunny'}
    res.end(`${urlObj.query.callback}(The ${JSON.stringify(data)}) `)}else{
    req.writeHead(404.'404 not found')
    res.end('404 Not Found')
  }
}).listen(2020)

console.log('listen to http://127.0.0.1:2020)
Copy the code

Front-end page JS:

<script>
  function showData(data) {
    console.log(data) //
  }
</script>
<script src="Http://127.0.0.1:2020/getWeather? callback=showData"></script>
Copy the code

The data is obtained in the function showData.

  1. CORS

Principle: When sending an Ajax request, the browser finds that the request does not comply with the same Origin policy and adds Origin to the request header. After the background receives a request, if it is sure to accept the request, it adds a response header: access-Control-allow-Origin; The browser determines whether the response header contains the current Origin value. If so, the browser will process the response and we can get the response data. If not, the browser will reject it.

Server code:

const http = require('http')
const url = require('url')

http.createServer((req, res) = >{
  let urlObj = url.parse(req.url, true)
  if(urlObj.pathname === '/getWeather'){
    res.setHeader('Access-Control-Allow-Origin'.'https://www.baidu.com')
    res.end(JSON.stringify( { city: 'hangzhou'.weather: 'sunny'}}))else {
    res.writeHead(404.'Not Found')
    res.end('not found')
    }

}).listen(9090)

console.log('You can access the getWeather interface at https://www.baidu.com! ')
Copy the code

Get data at www.baidu.com console:

fetch('http://127.0.0.1:9090/getWeather')
  .then(res= > res.json())
  .then(data= > console.log(data))
Copy the code

{city: “Hangzhou “, weather: “sunny”}

  1. Server transfer ()

Server code:

const http = require('http')
const url = require('url')

http.createServer((req, res) = >{
  let urlObj = url.parse(req.url, true)
  if(urlObj.pathname === '/bridge'){
    http.get(urlObj.query.url,req= >{
      let text = ' '
      req.on('data'.data= > text += data)
      req.on('end'.() = >{
        res.setHeader('Access-Control-Allow-Origin'.The '*')
        res.end(text)
      })
    })
  }
}).listen(8888)
console.log('listen to http://127.0.0.1:8888)
Copy the code
// The current code is running under another page
fetch('http://localhost:8888/bridge? url='+encodeURIComponent('http://baidu.com'))
.then(res= >res.text())
.then(data= > console.log(data))
Copy the code