域: 是指浏览器不能执行其他网站的脚本 跨域: 它是由浏览器的 同源策略 造成的,是浏览器对 JavaScript 实施的安全限制,所谓同源(即指在同一个域)就是两个页面具有相同的协议 protocol,主机 host 和端口号 port 则就会造成 跨域 跨域场景
场景的跨域场景有哪些,请参考下表 当前url 请求url 是否跨域 原因
1 http://www.autofelix.cn http://www.autofelix.cn/api.php 否 协议/域名/端口都相同 2http://www.autofelix.cn https://www.autofelix.cn/api.php 是 协议不同 3http://www.autofelix.cn http://www.rabbit.cn 是 主域名不同 4http://www.autofelix.cn http://api.autofelix.cn 是 子域名不同 5http://www.autofelix.cn:80 http://www.autofelix.cn:8080 是 端口不同
🎈 解决跨域的四种方式 nginx的反向代理 使用 nginx 反向代理实现跨域,是最简单的跨域方式 只需要修改 nginx 的配置即可解决跨域问题,支持所有浏览器,支持session,不需要修改任何代码,并且不会影响服务器性能 // nginx配置
1 server { 2 listen 81; 3 server_name www.domain1.com; 4 location / { 5 proxy_pass http://www.domain2.com:8080; #反向代理 6 proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名 7 index index.html index.htm; 8 9 # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用 10 add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为* 11 add_header Access-Control-Allow-Credentials true; 12 } 13}
jsonp请求 jsonp 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,兼容性好 兼容低版本IE,缺点是只支持 get 请求,不支持 post 请求 原理时网页通过添加一个 <script> 元素,向服务器请求 json 数据,服务器收到请求后,将数据放在一个指定名字的回调函数的参数位置传回来 //jquery实现
<script> $.getJSON('http://autofelix.com/api.php&callback=?', function(res) { // 处理获得的数据 console.log(res) }); </script>后端语言代理 可以通过一种没有跨域限制的语言中转一下,通过后端语言去请求资源,然后再返回数据 比如 http://www.autofelix.cn 需要调用 http://api.autofelix.cn/userinfo 去获取用户数据,因为子域名不同,会有跨域限制 可以先请求 http://www.autofelix.cn 下的 php 文件,比如 http://www.autofelix.cn/api.php,然后再通过该 php 文件返回数据
1 // api.php 文件中的代码 2public function getCurl($url, $timeout = 5) 3{ 4 $ch = curl_init(); 5 curl_setopt($ch, CURLOPT_URL, $url); 6 curl_setopt($ch, CURLOPT_HEADER, 0); 7 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 8 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 9 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 10 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 11 $result = curl_exec($ch); 12 curl_close($ch); 13 14 return $result; 15} 16 17$result = getCurl('http://api.autofelix.cn/userinfo'); 18 19return $result;
后端语言的设置 主要通过后端语言主动设置跨域请求,这里以 php 作为案例
1 // 允许所有域名访问 2header('Access-Control-Allow-Origin: *'); 3// 允许单个域名访问 4header('Access-Control-Allow-Origin: https://autofelix.com'); 5// 允许多个自定义域名访问 6static public $originarr = [ 7 'https://autofelix.com', 8 'https://baidu.com', 9 'https://csdn.net', 10]; 11 12// 获取当前跨域域名 13$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; 14if (in_array($origin, self::$originarr)) { 15 // 允许 $originarr 数组内的 域名跨域访问 16 header('Access-Control-Allow-Origin:' . $origin); 17 // 响应类型 18 header('Access-Control-Allow-Methods:POST,GET'); 19 // 带 cookie 的跨域访问 20 header('Access-Control-Allow-Credentials: true'); 21 // 响应头设置 22 header('Access-Control-Allow-Headers:x-requested-with,Content-Type,X-CSRF-Token'); 23}
推荐使用3A服务器,搭建环境杠杠的
