若是你有單獨的後端開發服務器 API,而且但願在同域名下發送 API 請求 ,那麼代理某些 URL 會頗有用。html
dev-server 使用了很是強大的 http-proxy-middleware 包。更多高級用法,請查閱其文檔。vue
在 localhost:3000
上有後端服務的話,你能夠這樣啓用代理:ios
proxy: { "/api": "http://localhost:3000" }
請求到 /api/users
如今會被代理到請求 http://localhost:3000/api/users
。git
若是你不想始終傳遞 /api
,則須要重寫路徑:github
proxy: { "/api": { target: "http://localhost:3000", pathRewrite: {"^/api" : ""} //後面可使重寫的新路徑,通常不作更改 } }
默認狀況下,不接受運行在 HTTPS 上,且使用了無效證書的後端服務器。若是你想要接受,修改配置以下:vue-cli
proxy: { "/api": { target: "https://other-server.example.com", secure: false } }
有時你不想代理全部的請求。能夠基於一個函數的返回值繞過代理。axios
在函數中你能夠訪問請求體、響應體和代理選項。必須返回 false
或路徑,來跳過代理請求。後端
例如:對於瀏覽器請求,你想要提供一個 HTML 頁面,可是對於 API 請求則保持代理。你能夠這樣作:api
proxy: { "/api": { target: "http://localhost:3000", bypass: function(req, res, proxyOptions) { if (req.headers.accept.indexOf("html") !== -1) { console.log("Skipping proxy for browser request."); return "/index.html"; } } } }
若是你使用的vue-cli開發 他一樣提供了 proxyTable 和上面的操做同樣瀏覽器
如下是我出於無奈改造的
const targetPath='http://172.16.3.48:8080';//服務器的地址 能夠是www.xxx.com const pathX='/*';//若是打包後接口地址爲fwone-central/orderinfo/* 則pathX='/*' 若是是/orderinfo/* 則pathX='' var keysArr=[ pathX+'/orderinfo/*', pathX+'/company/*', pathX+'/person/*', pathX+'/person/*/*', pathX+'/oncall/*', pathX+'/Tr/*', pathX+'/calldetail/*', pathX+'/customernotification/*', pathX+'/customernotification/*/*/*', pathX+'/sys/*', pathX+'/sys/*/*', pathX+'/invoice/*', pathX+'/contractservicedetails/*', pathX+'/customercomplain/*', pathX+'/callreminder/*', ] for(let i=0;i<keysArr.length;i++){ config.dev.proxyTable[keysArr[i]]={ target:targetPath, secure: false, changeOrigin: true, } } console.info(Object.keys(config.dev.proxyTable)) module.exports= config
我先說一下我爲何這麼作,咱們本地開發直接常規的寫法沒有問題可是若是部署到測試服務器上,一個tomcat跑多個項目咱們後端是用文件夾來區分項目的,可是這個區分後彷佛會影響接口路徑 ,也就是說
本來是‘/’ 如今變成了 ‘/fwone-central’
我一開始覺得這樣也很好解決 我直接把target 改爲 'http://172.16.3.48:8080/fwone-central' 接口報404
而後
'/fwone-central/orderinfo/*': { target:'http://172.16.3.48:8080', secure: false, changeOrigin: true, }, //這樣又ok 其實我看請求的地址是同樣同樣的
固然上面的問題還有坑 當你在請求數據的時候,本來是這樣的沒有問題 ,可是你部署後路徑改變了,這個請求路徑也就無效了
axios({ method: 'get', url:'/orderinfo/count' , params: {orderStateIds: [1, 2, 3, 4, 5, 6, 7, 8]} }).then(function (r) { if (r.data.code == 0) { //... } }); }).catch(function (error) { console.error(error); })
解決辦法,是有流傳已久的絕對路徑和公共路徑
window.localPath='http://localhost:8087/fwone-central' //他能夠定義在首頁隨時順着項目路徑修改 axios({ method: 'get', url:localPath+'/orderinfo/count' , params: {orderStateIds: [1, 2, 3, 4, 5, 6, 7, 8]} }).then(function (r) { if (r.data.code == 0) { //... } }); cb() }).catch(function (error) { console.error(error); })
還有最後一點須要注意路徑改變了打包後的靜態資源路徑也得改變 因此在vue-cli config.js index.js
build: { assetsSubDirectory: 'statics/mobile', //這是將靜態資源打包到指定的文件夾下 assetsPublicPath:'/fwone-central/', // 這是靜態資源的路徑 },
固然上面的絕對路徑能夠經過axios的全局配置來設置。