安装axios
npm i axios
在需要使用axios的地方引入axios
import axios from 'axios'
在methods进行配置
例:请求
http://localhost:5000/students(方式一)
http://localhost:5000/api/students(方式二),
<script>
import axios from 'axios'
export default {
name:'App',
methods: {
setStudents(){
axios.get('http://localhost:8080/api/students').then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败了',error.message)
}
)
}
},
}
</script>
配置代理服务器(在vue.config.js配置)
方式一:优点:配置简单,请求资源时直接发给前端(8080)即可
缺点:只能配置一个代理,不能灵活控制请求是否走代理
工作方式:当请求了前端不存在的资源时,该请求会转发给服务器(优先匹配前端资源)
devServer:{
proxy:'http://localhost:5000'
},
方式二:优点:可以配置多个代理,且可以灵活的控制请求是否走代理
缺点:配置略微繁琐,请求资源时必须加前缀
changeOrigin为true时,服务器收到的请求头中的host为:localhost:5000
changeOrigin为false时,服务器收到的请求头中的host为:localhost:8080
devServer: {
proxy: {
'/api': { //匹配所有以/api开头的路径
target: 'http://localhost:5000', //代理目标的基础路径
pathRewrite:{'^/api':''} //修改最终路径删除/api
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值
},
'/demo': {
target: 'http://localhost:5001',
pathRewrite:{'^/demo':''}
},
}
}