為什么會出現跨域?
出于瀏覽器的同源策略限制,同源策略(Sameoriginpolicy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響,可以說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實作,同源策略會阻止一個域的javascript腳本和另外一個域的內容進行互動,所謂同源(即指在同一個域)就是兩個頁面具有相同的協議(protocol),主機(host)和埠號(port),
什么是跨域?
當一個請求url的協議、域名、埠三者之間任意一個與當前頁面url不同即為跨域,
情況如下圖所示:

舉例
我在本地啟動一個服務,服務器監聽埠3000

我們在vue專案直接去調該服務下介面會報錯

這是因為我們發送請求的埠是8081,與服務器的埠不一致,導致跨域問題,
解決方案
根據服務器之間發請求不存在跨域,設定代理服務器,
查看vue專案根目錄,如果有vue.config.js檔案(一般是自己引入),打開并找到devServer{ }處,加上以下代碼:
devServer: {
// 設定為0.0.0.0則所有的地址均能訪問
host: '0.0.0.0',
port: 8080,
https: false,
hotOnly: false,
// 跨域問題解決 代理(關鍵部分)
proxy: {
'/api': {
target: 'http://localhost:3000', // 注意!此處為后端提供的真實介面
changeOrigin: true, // 允許跨域
pathRewrite: {
// 如果介面中是沒有api的,那就直接置空,'^/api': '',
// 如果介面中有api,那就得寫成{'^/api':'/api'}
'^/api': ''
}
}
}
}
核心部分

如果沒有vue.config.js檔案,那就找到專案中config檔案夾中的index.js檔案

找到proxyTable{ }處,加上與上面一樣的代碼

此時停止vue專案,重新啟動

解決跨域問題,請求成功,若專案打包上線可使用Nginx設定代理服務器,
vue.config.js標準配置
// vue.config.js
const path = require('path');
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/site/vue-demo/' : '/', // 公共路徑
indexPath: 'index.html' , // 相對于打包路徑index.html的路徑
outputDir: process.env.outputDir || 'dist', // 'dist', 生產環境構建檔案的目錄
assetsDir: 'static', // 相對于outputDir的靜態資源(js、css、img、fonts)目錄
lintOnSave: false, // 是否在開發環境下通過 eslint-loader 在每次保存時 lint 代碼
runtimeCompiler: true, // 是否使用包含運行時編譯器的 Vue 構建版本
productionSourceMap: !IS_PROD, // 生產環境的 source map
parallel: require("os").cpus().length > 1, // 是否為 Babel 或 TypeScript 使用 thread-loader,該選項在系統的 CPU 有多于一個內核時自動啟用,僅作用于生產構建,
pwa: {}, // 向 PWA 插件傳遞選項,
chainWebpack: config => {
config.resolve.symlinks(true); // 修復熱更新失效
// 如果使用多頁面打包,使用vue inspect --plugins查看html是否在結果陣列中
config.plugin("html").tap(args => {
// 修復 Lazy loading routes Error
args[0].chunksSortMode = "none";
return args;
});
config.resolve.alias // 添加別名
.set('@', resolve('src'))
.set('@assets', resolve('src/assets'))
.set('@components', resolve('src/components'))
.set('@views', resolve('src/views'))
.set('@store', resolve('src/store'));
},
css: {
extract: IS_PROD,
requireModuleExtension: false,// 去掉檔案名中的 .module
loaderOptions: {
// 給 less-loader 傳遞 Less.js 相關選項
less: {
// `globalVars` 定義全域物件,可加入全域變數
globalVars: {
primary: '#333'
}
}
}
},
devServer: {
overlay: { // 讓瀏覽器 overlay 同時顯示警告和錯誤
warnings: true,
errors: true
},
host: "localhost",
port: 8080, // 埠號
https: false, // https:{type:Boolean}
open: false, //配置自動啟動瀏覽器
hotOnly: true, // 熱更新
// proxy: 'http://localhost:8080' // 配置跨域處理,只有一個代理
proxy: { //配置多個跨域
"/api": {
target: "http://172.10.10.12:3000",
changeOrigin: true,
// ws: true,//websocket支持
secure: false,
pathRewrite: {
"^/api": ""
}
},
"/api2": {
target: "http://172.10.12.13:8089",
changeOrigin: true,
//ws: true,//websocket支持
secure: false,
pathRewrite: {
"^/api2": "/"
}
},
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/375921.html
標籤:其他
