解决跨域

170 阅读1分钟

一.

  1. protocol/hostname/port(协议/域名/端口):其中任何一个不同既是跨域;

二.规避浏览器同源策略

y.localhost.com访问x.localhost.com

1.JSONP(script src Get,不支持POST,因此url有长度限制)

html:
<!DOCTYPE html>
<html>
<head>
    <title>JSONP</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.bootcss.com/require.js/2.3.4/require.min.js"></script>
</head>
<body>
    <div class="container"></div>
    <script src="./1.js"></script>
</body>
</html>

js:
/**
 * 方法1
 */
window.xxx = function (value) {
  console.log(value)
}

var script = document.createElement('script')
script.src = 'http://x.localhost.com:7001/json?callback=xxx'
document.body.appendChild(script)

/**
 * 方法2
 */
// require(['http://x.localhost.com:7001/json?callback=define'], function (value) {
//   console.log(value)
// })

2.document.domain + iframe(适用于主域名一致情况下)
3.localtion.hash + iframe(不方便,有长度限制)
4.window.name + iframe(兼容性)
5.postMessage (主域名一致)
6.CORS(服务器配置)

html:
<!DOCTYPE html>
<html>
<head>
    <title>JSONP</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
    <div class="container"></div>
    <script src="./2.js"></script>
</body>
</html>

js:
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText).msg)
  }
}
//ajax中,xhr.withCredentials = true:当前请求为跨域类型时在请求中协带cookie
xhr.withCredentials = true
xhr.open('GET', 'http://x.localhost.com:7001/cros')
xhr.send(null)

js(服务器端):
module.exports = app => {  class CrosController extends app.Controller {    * index(req) {      this.ctx.set('Access-Control-Allow-Origin', 'http://y.localhost.com:7001')      this.ctx.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');      this.ctx.set('Access-Control-Allow-Headers', 'X-Requested-With, User-Agent, Referer, Content-Type, Cache-Control');      this.ctx.set('Access-Control-Allow-Credentials', 'true');      this.ctx.body = { msg: 'hello world' }    }  }  return CrosController}

7.服务器转发(非跨域,占用主域带宽)

   nginx配置‘proxy_pass’,将原本跨域的请求变成了同域

8.WebSocket(实现成本)