CORS跨域

跨域是指在浏览器客户端,产生的行为。在curl客户端不存在跨域。

浏览器跨域案例展示:

server.js

const http = require('http')
const fs = require('fs')

http.createServer((req, res) => {
  console.log('request come', req.url)

  const html = fs.readFileSync('test.html', 'utf8')
  res.writeHead(200, {
    'Content-Type': 'text/html'
  })
  res.end(html)

}).listen(8888)

console.log('server listening on 8888')

test.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
  var xhr = new XMLHttpRequest()
  xhr.open('GET', 'http://127.0.0.1:8887/')
  xhr.send()
</script>
</body>
</html>

node server.js后,访问 http://localhost:8888/

   因为http://127.0.0.1:8887 的响应头里,没有允许http://127.0.0.1:8888请求数据。所以根据同源政策,浏览器将http://127.0.0.1:8887的响应数据屏蔽了。

当我们在8887的响应头里允许8888访问后,浏览器就会将响应内容解锁。

服务端解决跨域:

server2.js

const http = require('http')

http.createServer((req, res) => {
  console.log('request come', req.url)

  res.writeHead(200, {
    'Access-Control-Allow-Origin': '*'
  })
  res.end('123')
}).listen(8887)

console.log('server listening on 8887')

这里的 'Access-Control-Allow-Origin': '*' 是指允许所以的地址访问。

允许指定的地址访问可以这么写 'Access-Control-Allow-Origin': 'http://127.0.0.1:8888'   'Access-Control-Allow-Origin': 'http://baidu.com' 

jsonp解决跨域:[原理: 浏览器允许link标签、script标签、img标签等,跨域加载数据]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<!-- <script>
  var xhr = new XMLHttpRequest()
  xhr.open('GET', 'http://127.0.0.1:8887/')
  xhr.send()
</script> -->
<script src="http://127.0.0.1:8887/"></script>
</body>
</html>
原文地址:https://www.cnblogs.com/ladybug7/p/12334460.html