方法一
在vue.config.js中添加如下配置:
module.exports = {
proxy: 'http://localhost:5000'
}
请求时:
axios.get('http://localhost:8080/students').then() ...
说明:
- 1. 优点:配置简单,请求资源时直接发给8080即可。
- 2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理(比如当前端就有匹配的资源时,则会直接将该资源返回,而不会去真正的服务器上查找)。通过方法二可以解决这两个问题。
- 3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)。
方法二
编写vue.config.js配置具体代理规则:
module.exports = {
devServer: {
proxy: {
'/api1': { // 匹配所有以'/api1'开头的请求路径
target: 'http://localhost:5000', // 代理目标的基础路径
pathRewrite: {'^/api1': ''}, // 路径重写
changeOrigin: true
},
'/api2': {
target: 'http://localhost:5001',
pathRewrite: {'^/api2': ''},
changeOrigin: true
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为:localhost: 5000
changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
changeOrigin默认值为true
*/
请求时:
// 必须带上前缀
axios.get('http://localhost:8080/api1/students').then() ...
说明:
- 1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
- 2. 缺点:配置略微繁琐,请求资源时必须加前缀。