先看一个demo
文件
vue.config.js(脚手架的配置文件)
module.exports = {
lintOnSave: false,
devServer: {
open: process.platform === 'darwin',
host: '0.0.0.0',
port: 8011,
// https: false,
// hotOnly: false,
// // 查阅 https://github.com/vuejs/vue-doc-zh-cn/vue-cli/cli-service.md#配置代理
// proxy: null, // string | Object
// before: app => {
// // `app` 是一个 express 实例
// }
proxyTable: {
'/api': { //这里最好有一个 /
target: 'http://144.15.15.52:8888', // 后台接口域名
// ws: true, //如果要代理 websockets,配置这个参数
// secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '/api'
}
}
}
},
}
如果关键代理的配置是这样的
proxyTable: {
'/api': { //这里最好有一个 /
target: 'http://144.15.15.52:8888', // 后台接口域名
// ws: true, //如果要代理 websockets,配置这个参数
// secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': ''
} //这个属性是必须要写的
}
}
那么产生的效果就是
http://144.15.15.52:8888=/api
一个具体的接口地址等价于一个指定的开头的请求地址。
但是因为加上了具体的pathRewrite,那么就变成了其他的等价关系
http://144.15.15.52:8888/api=api
再举一个例子
proxy: {
//代理转发
'^/api/gg': {
target: `http://144.15.52.125:2155`, //后端服务地址
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api/gg': '/api/mm/v1',
},
},
那么最终等价关系就等于
http://144.15.52.125:2155/api/mm/v1 ==== /api/gg
nginx中的配置同样为
location /api/gg/ {
proxy_pass http://144.15.52.125:2155/api/mm/v1/;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_cookie_path / "/; httponly; secure; SameSite=None";
}