一、安装axios
npm install axios
二、导入axios
在main.js文件中添加
import axios from 'axios'
Vue.prototype.$axios = axios;
Vue.use(axios)
经过上述两个步骤,axios导入成功。
三、遇到的问题
VUE启动的端口为localhost:8080 访问的后端为 localhost:8090,在前端访问后端接口时,出现下列错误,出现了跨域问题
四、解决方法:
4.1 在vue.config.js文件中添加
devServer: {
proxy: {
'/api': {
// 目标的路径
target: 'http://localhost:8090', //也就是接口地址
// 允许跨域
changeOrigin: true,
// 重写跨域
pathRewrite: {
'^/api': ''
}
}
}
}
4.2
然后再.vue文件中的script中添加下述代码
this.$axios({
url:"/api/toLogin",//请求的后台接口
method:"get",//get请求方式
params:this.data //传给后台的参数
}).then(response=>{
//请求成功
}).catch(error=>{
//请求失败
});
注意:其中的/api 为在vue.config.js中的/api,即利用/api代理了http://localhost:8090
五、结果
成功发送请求
后台也能够接收到请求。