前端開發(fā)解決跨域4種方案

一、什么是跨域?

? ? ? 跨域是瀏覽器不能執(zhí)行其它網(wǎng)站的一些資源,如js?圖片、dom?視頻、音頻等cookie? local storage 和index Db無法讀取 、Ajax 請求無法發(fā)送等,受瀏覽器同源策略的影響,只要協(xié)議、域名、端口號三個中有任意一個不一樣就是跨域。

二、解決方案

1?JSONP方案

利用瀏覽器對<script>標簽沒有跨域限制,通過src屬性發(fā)送帶有回調(diào)函數(shù)參數(shù)的get請求,在 callback函數(shù)中前端拿到函數(shù)返回數(shù)據(jù)。

<script>

? ? let script = document.createElement('script');

? ? script.type = 'text/javascript';

? ? script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';

? ? document.head.appendChild(script);

? ? function handleCallback(res) {

? ? ? ? alert(JSON.stringify(res));

}

</script>

只能發(fā)送get請求


2、跨域資源共享CORS cross-origin resource sharing 允許瀏覽器相框原服務(wù)器發(fā)出XMLHttpRequest請求

在vue中通過vue-cli進行配置,在本地開發(fā)環(huán)境的請情況下,在vue.config.js中的devServer對象中添加headers: { "Access-Control-Allow-Origin": "*"},這個表示 向所有請求的herder中添加Access-Control-Allow-Origin? 為*則表示接受任意域名的請求 這里后端也需要配置,接收到這個配置項后后端處理。

3、nginx反向代理接口跨域

通過監(jiān)聽端口服務(wù),利用proxy_pass進行反向代理

#proxy服務(wù)器

server {

? ? listen? ? ? 81;

? ? server_name? exname;#這里隨便寫

? ? location / {?

? ? ? ? proxy_pass? http://www.xxxx.com:8080;? #反向代理

? ? ? ? index? index.html index.htm;

? ? }

}

4、使用nodejs中間件代理跨域

在vue項目的開發(fā)環(huán)境中,配置vue.config.js

module.exports = {

? ? entry: {},

? ? module: {},

? ? ...

?devServer: {

? ? port: port,

? ? open: true,

? ? overlay: {

? ? ? warnings: false,

? ? ? errors: true

? ? },

? ? // 代理選項

? ? // 可以有多個代理選項

? ? proxy: {

? ? ? // key表示如果一旦請求地址和它吻合 ,就會觸發(fā)代理,代理的信息 在對象 value

? ? ? // localhost:8888/api/user ?=> http://ihrm-java.itheima.net/api/user ?這是我們需要的地址

? ? ? // localhost:8888/api/user ?=> http://ihrm-java.itheima.net/user

? ? ? '/api': {

? ? ? ? target: 'http://ihrm-java.itheima.net/', // 要代理的目標地址

? ? ? ? // target: 'http://127.0.0.1:3000', // 要代理的目標地址

? ? ? ? changeOrigin: true // 是否跨域

? ? ? ? // localhost:8888/api/user => 觸發(fā)代理 =>

? ? ? ? // ?http://www.baidu.com/user ?想要這種

? ? ? ? // ?http://www.baidu.com/api/user ?下面是目前的

? ? ? ? // pathRewrite: {

? ? ? ? // ? '^/api': '' // 相當于將跨域代理之后的地址進行再次替換 就可以將 /api去掉

? ? ? ? // }

? ? ? }

? ? }

? ? // before: require('./mock/mock-server.js')

? },

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容