配置代理
1、方式一:
安装:axios
yarn add axios
axios.get('http://localhost:8080/students').then(
response => {
console.log(response.data)
},
error => {
console.log(error.message)
}
)
vue.config.js中配置代理
devServer:{
proxy:'http://localhost:5000'
}
优点:配置简单,请求资源时直接发给前端即可;
缺点是,只能配置一个代理,不能灵活的控制请求是否走代理
2、方式二:
devServer: {
proxy: {
//请求前缀
'/api': {
target: 'http://localhost:5000',
pathRewrite:{
'^/api':''//重写路径
},
ws:true,//用于支持websocket
changeOrign:true//false请求来自于代理服务器,true请求来自于真是服务器
}
}
}
axios.get('http://localhost:8080/api/students').then(
response => {
console.log(response.data)
},
error => {
console.log(error.message)
}
)
优点:可以配置多个代理,且可以灵活控制请求是否走代理;
缺点:配置略微繁琐,请求资源时必须加前缀。
vue-resource(了解)
安装
yarn add vue-resource
引入,main.js中
import VueResource from 'vue-resource'
Vue.use(VueResource)
用法和axios一模一样,只不过是this.$http调用
this.$http.get('https://dog.ceo/api/breed/husky/images/random').then(
response => {
console.log(response.data)
},
error => {
console.log(error.message)
}
)