如何解决跨域问题?

81 阅读1分钟

跨域问题

原因:浏览器的同源策源 浏览器从一个域名获取的网页去请求另一个域名的资源时,域名,端口,协议任何一个不同,都是跨域。

常见的解决方案有三种

  • cors
由服务端解决,添加cors功能模块
前端:无操作
  • jsonp 利用script脚本的src不受同源策略限制的特点 服务器:返回特定的jsonp格式数据
  <?php
  header('Content-type:application/json');
  //获取回调函数名
  $jsoncallback=htmlspecialchars($_REQUEST['jsoncallback']);
  //json数据
  $json_data='["customername1","customername2"]';
  //输出jsonp格式的数据
  echo $jsoncallback."(".$json_data.")"
  ?>   

前端:发送特定的jsonp格式数据到服务器

<div id="divCustomers"></div>
<script type="text/javascript">
   function callbackFunction(result,methodName){
       var html='<ul>';
       for(var i=0;i<result.length;i++){
           html+='<li>'+result[i]+'</li>'       
       }
       html+='</ul>'
       document.getElementById('divCustomers').innerHTML=html   
   }
</script>
<script type="text/javascript"/ src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction">
</script>
  • 代理proxy
// vue,angular 都提供固定的方式设定代理
//vue-cli3里面的vue。config.js做配置
deServer:{
    proxy:{
        '/rng':{ //这里最好有一个
             target:'http://45.105.124.130:8081',//后台接口域名
             ws:true,//如果代理websockets,配置这个参数
             secure:false,//如果https接口,需要配置这个参数
             changeOrigin:true,//是否跨域
             pathRewrite:{
                 '^/rng':''             
             }                                 
        }    
    }
}