“跨域”是瀏覽器出于安全方面考慮作出的限制,如果不在同一域名下訪問接口的話就會產生跨域問題;一般ajax請求如果因為跨域問題報錯的話,一般會有以下提示:
post request is No 'Access-Control-Allow-Origin' header is present on the requested resource.'
如果看到上面的報錯,那你肯定是跨域訪問了。
其實解決辦法也很簡單,統一域名就可以了,現在由于一些前后端分離的方案無法統一域名,其實最好的辦法還是在服務端做手腳,加上以下header
> header("Access-Control-Allow-Origin:*");
前端即可直接獲取到數據。
這又叫做跨域資源共享(CORS)
如果這種辦法也不能用的話,就只能在前端采取一些手段去實現跨域了,目前主流的跨域方法有以下幾種
jsonp
通常為了減輕web服務器的負載,我們把js、css,img等靜態資源分離到另一臺獨立域名的服務器上,在html頁面中再通過相應的標簽從不同域名下加載靜態資源,而被瀏覽器允許,基于此原理,我們可以通過動態創建script,再請求一個帶參網址實現跨域通信。
但是有個缺點,只能實現get一種請求。
1) 原生實現
<script>
var script = document.createElement('script');
script.type = 'text/javascript'; // 傳參并指定回調執行函數為onBack
script.src = 'http://data/login?user=admin&callback=onBack'; // 接口地址
document.head.appendChild(script); // 回調執行函數
function onBack(res) {
alert(JSON.stringify(res));
}
</script>
服務端返回如下(返回時即執行全局函數):
onBack({"status": true, "user": "admin"})
2)JQuery
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get', dataType: 'jsonp', // 請求方式為jsonp
jsonpCallback: "onBack", // 自定義回調函數名
data: {}
});
3) vue.js
this.$http.jsonp('http://data/login', {
params: {},
jsonp: 'onBack'
}).then((res) => {
console.log(res);
})
另外還有個jsonp庫可用,方法如下
import jsonp from 'jsonp'
jsonp(url, options, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
}
document.domain + iframe跨域
此方案僅限主域相同,子域不同的跨域應用場景。
實現原理:兩個頁面都通過js強制設置document.domain為基礎主域,就實現了同域。
1.)父窗口:(http://www.domain.com/a.html))
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
document.domain = 'domain.com';
var user = 'admin';
</script>
2.)子窗口:([http://child.domain.com/b.html)
<script>
document.domain = 'domain.com'; // 獲取父窗口中變量
alert('get js data from parent ---> ' + window.parent.user);
</script>
location.hash + iframe
實現原理: a欲與b跨域相互通信,通過中間頁c來實現。 三個頁面,不同域之間利用iframe的location.hash傳值,相同域之間直接js訪問來通信。
具體實現:A域:a.html -> B域:b.html -> A域:c.html,a與b不同域只能通過hash值單向通信,b與c也不同域也只能單向通信,但c與a同域,所以c可通過parent.parent訪問a頁面所有對象。
1.)a.html:http://www.domain1.com/a.html
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// 向b.html傳hash值 setTimeout(function() {
iframe.src = iframe.src + '#user=admin';
}, 1000);
// 開放給同域c.html的回調方法
function onCallback(res) {
alert('data from c.html ---> ' + res);
}
</script>
2.)b.html:http://www.domain2.com/b.html
<iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe><script>
var iframe = document.getElementById('iframe');
// 監聽a.html傳來的hash值,再傳給c.html
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
};
</script>
3.)c.html:(http://www.domain1.com/c.html))
<script>
// 監聽b.html傳來的hash值
window.onhashchange = function () {
// 再通過操作同域a.html的js回調,將結果傳回 window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
};
</script>
more
此外還有以下方法
- nginx反向代理接口跨域
- Nodejs中間件代理跨域
- WebSocket協議跨域
ps:
另外值得一提的是vue-cli + webpack也可通過配置實現1次跨域,不過僅限開發環境,在項目上線前由于某些限制不能做到同域的時候,采用這種方式是很靈活的
在開發環境下,由于vue渲染服務和接口代理服務都是webpack-dev-server同一個,所以頁面與代理接口之間不再跨域,無須設置headers跨域信息了。
module.exports = {
entry: {},
module: {},
...
devServer: {
historyApiFallback: true,
proxy: [{
context: '/login',
target: 'http://www.domain2.com:8080', // 代理跨域目標接口
changeOrigin: true,
cookieDomainRewrite: 'www.domain1.com' // 可以為false,表示不修改
}],
noInfo: true
}
}