【解决跨域问题】

1. 跨域是什么

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。

2. 同源策略

基于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能。同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)。

3. 常用解决跨域的方法

  • JSONP
  • CORS
  • Nginx
  • document.domain
  • window.name
  • postMessage+iframe
3.1 JSONP

利用【script便签】不受同源策略的影响的,立即下载并执行函数的特性。

 
// 1.回调函数
function handleResponse(data){
  console.log(data);
}
// 2. script
var script = document.createElement('script');
// 请求地址
script.src = 'http://test.com/json?callback=handleResponse'; document.body.insertBefore(script,document.body.firstChild);

缺点

  • 只适用于get请求
  • 不知道请求是否成功
  • 安全问题
3.2 CORS
  1. 概念
    CORS,即跨域资源共享(Cross-origin resource sharing)。
  2. 具体操作
    在响应头加 Access-Control-Allow-Origin: http://test.com 即可

一般当请求方式为 GET 、HEAD、 POST,Content-Type类型为 text/plain、multipart/form-data 、application/x-www-form-urlencoded 时,

// 允许 http://test.com这个源的请求
Access-Control-Allow-Origin: http://test.com  
// 允许 所有源的请求
Access-Control-Allow-Origin: * 
3.3 Nginx

修改nginx.conf,反向代理

# / 所有以 apis开头的请求都会分发到 myserver 
location ^~ /apis/ {
     proxy_pass http://myserver; 
     proxy_set_header X-real-ip $remote_addr;
     proxy_set_header Host $http_host;
}
3.4 document.domain

只适用于二级域名一样的情况
如:a.test.com,b.test.com
可以在页面上设置 document.domain=‘test.com’ 来实现跨域请求

3.5 window.name

在不关闭当前页面的情况下,如果设置了window.name =‘test’ 并跳转到 location.href,则 window.name 还是test

3.6 postMessage+iframe

用于获取嵌入页面中的第三方数据

// 发消息
<div>
   <div id="color">Frame Color</div>
</div>
<div>
   <iframe id="child" src="http://b.com/b.html"></iframe>
</div>
window.onload=function(){
	// 嵌入的这个页面有交互
   window.frames[0].postMessage('getcolor','http://b.com');
}
// 收消息
window.addEventListener('message',function(e){
      console.log(e)
},false);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值