安装npm install --save axios vue-axios
importaxiosfrom'axios'
importVueAxiosfrom'vue-axios'
Vue.use(VueAxios, axios)
封装
在src文件夹下创建一个axios文件夹,添加一个request.js
import axiosfrom 'axios';
//api的base_url
let baseUrl=process.env.baseURL;
//创建axios实例
const service=axios.create({
vaseURL:baseUrl,
timeout:5000
})
//使用request拦截器对axios请求配置做统一处理 添加请求拦截器
service.interceptors.request.use(
config => {
let url = config.url;
// let code = config.code;
// config.headers = getHeader(url, code) // 让每个请求携带自定义签名
return config
},
error => {
console.log(error)// for debug 11
Promise.reject(error)
}
)
// response 拦截器 添加响应拦截器
service.interceptors.response.use(
response => {
const res = response.data
if (res.code ===200) {
return response.data
}else if(res.code ===407){
console.log("Token失效跳转登陆页面");
}else {
return Promise.reject('error')
}
},
error => {
console.log('err' + error)// for debug
return Promise.reject(error)
// }
}
)
//暴漏出去
export default service
封装请求
import requestfrom '../axios/request.js'
//get
export function getList(data) {
return request({
url:'xxxxx',
method:'get',
data,
})
}
//post
export function getListDetail(data) {
return request({
url:'xxxx',
method:'post',
data,
})
}
页面调用
import *as Api from '../api/api.js';
load() {
Api.getList().then(
res => {
this.lists=res.result;
}).catch(error => {
console.log(error);
});
}
}