axios的封装
"use strict";
import Vue from 'vue';
import axios from "axios";
import router from '../router'
let config = {
baseURL:'',
timeout: 60*1000,
};
const _axios = axios.create(config);
Vue.prototype.$http = _axios
_axios.interceptors.request.use(
function (config) {
const token = window.sessionStorage.getItem('token');
if (token) {
config.headers['Authorization'] = token;
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
_axios.interceptors.response.use(
function (response) {
if (response.data.token) {
window.sessionStorage.setItem('token', response.data.token);
}
return response;
},
function (error) {
console.log(error.response.status, '??')
if (error.response.status === 401) {
window.sessionStorage.removeItem('token');
console.log(error.response.data.error.message, 'token过期');
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
})
} else if (error.response.status === 500) {
alert('服务器错误,请稍后再试')
return Promise.reject('服务器出错:', error.response.data);
}
return Promise.reject(error);
}
);
Plugin.install = function (Vue, options) {
console.log(options);
Vue.axios = _axios;
window.axios = _axios;
Object.defineProperties(Vue.prototype, {
axios: {
get() {
return _axios;
}
},
$axios: {
get() {
return _axios;
}
},
});
};
Vue.use(Plugin)
export const $http = _axios
export default Plugin;
axios使用说明
- 因为在封装axios时执行了
Vue.prototype.$http = _axios
,所以我们在发起请求时按照如下模式发起请求:
async fn(){// fn是函数名,根据自己需求命名
// get请求
const { data: res } = await this.$http.get(url,{params:{}});//第二个参数为请求参数,如果需要
// post请求
const { data: res } = await this.$http.post(url,{});//第二个参数为请求参数,如果需要
if (res.code !== 200) return this.$message.error(res.message);
console.log(res.data);// res.data返回的数据
},