使用场景
如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。
原理解释
当你配置了 changeOrigin: true,所有请求先会请求的你本地的服务器,然后通过http-proxy-middleware代理到你配置的 target 服务器。
module.exports = {devServer: {proxy: {'/api': {target: 'https://xx.dxy.net/',changeOrigin: true,ws: true,pathRewrite: {'^/api': ''}}}}}
本地请求的接口写法:
axios.get('/api/admin/userInfo').then(res => {console.log(res)})
如果你本地起的服务为:http://localhost:8081,则接口请求的 request 会是:http://localhost:8081/admin/userInfo,但实际请求已经代理为https://xx.dxy.net/admin/userInfo,这样就就能在本地调试不同域名下的接口了。
关键解释
- ‘/api’:类似正则作用,代理时会将 /api 替换为 target
- changeOrigin:是否开启代理
- pathRewrite:重写代理路径
