一、首先介绍一下axios配置
1、安装axios
npm install --save axios
2、在入口main.js中导入axios 并将axios写入vue的原型,这样就能更简单的使用。
import Axios from 'axios'
Vue.prototype.$axios = Axios
3、在项目里愉快的使用axios啦
当然了要记得在mounted钩子函数中调用方法
sendGet(){
this.$axios.get('url,{
params:{//入参
}
})
.then(resp => {//出参
console.log(resp.data);
}).catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
这段代码可以在vue的mounted钩子或者methos里面使用。
url这里是你要请求的接口。
二、跨域问题
1:打开config/index.js
|
|
在这里面找到proxyTable{},改为这样:
1 2 3 4 5 6 7 8 9 |
|
2:在需要调接口的组件中这样使用:
1 2 3 4 5 6 7 8 |
|
注意:原接口:http://http://121.41.130.58:9090/yt_api/login/doLogin
页面调用:http://localhost:8081/api/yt_api/login/doLogin ——这里多了一个/api/不是多余的,不要删
三、填坑axios跨域配置
做完上述操作基本上就可以正常运行了,但是有的配置完成之后却调不通接口报这样的错
注意看 你的/apI没有转化成 http://121.41.130.58:9090 你的
proxyTable里的配置没有生效
那么这个时候你需要在proxyTable里加如下
proxyTable: {
cssSourceMap: false,
'/api/*': {
target: ' http://121.41.130.58:9090',
changeOrigin: true,
pathRewrite: { '^/api': '' },
secure: false
}
}
配置上这些之后 重新启动你的项目 问题就解决了
欢迎指正补充。