使用vue-cli這種腳手架工具開發時,由於項目本身啟動本地服務是需要占用一個端口的,所以必然會產生跨域的問題 這里記錄下解決方案
在conf index.js 對應啟動配置中設置代理
proxyTable: {
"/localhost_api":{
target: 'http://127.0.0.1:800/http',//目標接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/localhost_api': '' //重寫接口
}
}
}
關於pathRewrite 參數
'^/localhost_api'是一個正則表達式
'^/localhost_api' 應該拆分成 ‘^’ 和 '/localhost_api' 兩個字符串,其中 ‘^’ 匹配的是字符串最開始的位置。
也就是說,axios 的請求URL寫成了 '/
localhost_api/myAPI/path'
的話,最后會在經過 http-proxy-middleware
的代理服務器時,會變成 '/myAPI/path'
,然后代理到 http://localhost:8080
這個代理服務器下面。