vue-cli 中配置代理服务器
- 项目根目录下新建 vue.config.js 文件
module.exports = {
// 开启代理服务器
devServer: {
proxy: "http://localhost:3000", // 前端请求 http://localhost:8080 会被自动代理到这个地址中
}
}
- 当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配 public 目录中的内容)
module.exports = {
// 开启代理服务器
devServer: {
proxy: {
'/api1': { // 匹配所有 /api1 开头的请求路径
target: 'http://localhost:5000', // 代理的基础路径
pathRewrite: {'^/api1': ''}, // 路径重写, 将 /api1替换为空字符串
changeOrigin: true,
},
'/api2': { // 匹配所有以 /api2 开头的请求路径
target: 'http://localhost:5001', // 代理的基础路径
pathRewrite: {'^/api2': ''}, // 将路径中的 /api2 替换为 空字符串
}
}
}
}
- changeOrigin 设置为 true 时 服务器收到的请求头中的 host 为 localhost:5000
- changeOrigin 设置为 false 时 服务器收到的请求头中的 host 为 localhost:8080
- changeOrigin 默认为 true