Vue-代理配置
在vue中一般和axios一起搭配使用,使用vue脚手架来配置代理
配置代理可以有效解决我们前端遇到的跨域问题
1.在vue.config.js中添加如下配置:
方法一:在vue.config.js中添加如下配置:
proxy:"http://localhost:5000"
}
以上代码说明:
以下代码为配置代理的方法一
- 优点:配置简单,请求资源时直接发给前端(8080)即可。
- 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
- 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
方法二:编写vue.config.js配置具体代理规则:
module.exports = {
devServer: {
proxy: {
'/demo1': {// 匹配所有以 '/demo1'开头的请求路径
target: 'http://localhost:5000',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/demo1': ''}
},
'/demo2': {// 匹配所有以 '/demo2'开头的请求路径
target: 'http://localhost:5001',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/demo2': ''}
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
changeOrigin默认值为true
*/
js
以上代码说明:
- 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
- 缺点:配置略微繁琐,请求资源时必须加前缀。
在app.vue中利用axios发送请求
<template>
<div>
<button @click="getStudents">点击获取学生信息</button>
<button @click="getCars">点击获取汽车信息</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'App',
components:{},
methods:{
getStudents(){
axios.get("http://localhost:8080/api1/students").then(
response =>{
console.log("成功了" , response.data);
},
error=>{
console.log("失败了" , error.message);
}
)
},
getCars (){
axios.get("http://localhost:8080/api2/cars").then(
response=>{
console.log("成功了" , response.data);
},
error=>{
console.log("失败了", error.message);
}
)
}
}
}
</script>
最后记得重启,你就成功的利用vue配置了一个代理服务器。