若是你有单独的后端开发服务器 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的全局配置来设置。