瀏覽器同源策略以及跨域的方法

同源策略

1.同源策略是瀏覽器的一個安全功能,兩個頁面的協議,端口和域名都相同,則兩個頁面具備相同的
例:https://segmentfault.com:81/u/mount_chan
其中https爲協議,segmentfault爲域名,81爲端口號,三者必須一致的兩個頁面才能成爲同源,才能夠進行ajax請求前端

URL status reason
https://segmentfault.com:81/u/mount_chan2 success 同源
https://segmentfault.com:80/u/mount_chan fail (80)不一樣端口
http://segmentfault.com:81/u/mount_chan fail (http)不一樣協議
https://baidu.com:81/u/mount_chan fail (baidu)不一樣域名

2.因爲同源策略的影響,咱們在實際開發中想要調取其餘協議,如百度地圖,定位信息等,這些都會限制,所以咱們要想實現功能,就必須用到跨域的方法,這一塊我常常用jsonp進行跨域請求。vue

jsonp原理
  1. 因爲script標籤的src和img標籤的src,以及link標籤的href他們沒有被同源策略所限制,所以能夠利用這個「漏洞」進行跨域請求。以下面jquery例子。
$('#a').click(function(){
            var frame = document.createElement('script');
            frame.src = 'https://segmentfault.com/write?freshman=1&callback=mount_chan';
            $('body').append(frame);
        });

其中callback裏面裝的是返回的數據,再看以下:jquery

$('#a').click(function(){
            var frame = document.createElement('script');
            frame.src = 'https://segmentfault.com/write?freshman=chan&callback=mount_chan';
            $('body').append(frame);
        });
        function mount_chan(res){
          console.log(res.message)
        }

咱們聲明瞭一個mount_chan函數,若是服務端接口到get請求,返回的是mount_chan({message:'hello',chan:chen}),這樣的話就能夠在服務端把數據經過函數執行傳參的方式實現數據傳遞。如此即可實現jsonp跨域請求。callback在前端中聲明傳給後端的函數名字,後端接收以後將數據在傳給前端。ajax

  1. 在vue中使用jsonp。
  • 首先在項目中執行命令
npm install vue-jsonp --save
  • src/main.js中添加
import vueJsonp from 'vue-jsonp'
Vue.use(vueJsonp)
  • 而後就能夠直接使用了
let obj = { 'location':item.point.lat+','+item.point.lng, 'output':'json', 'ak':'\*\*\*' } this.$jsonp('https://api.map.baidu.com/geocoder/v2/', obj).then(res => {
                  console.log(res) this.
                }).catch(err => {
                  console.log(err)
                })
總結
  1. 同源策略要搞清楚。
  2. jsonp原理以及實現方法,要在實際開發中靈活運用。
相關文章
相關標籤/搜索