"use strict";
import Vue from 'vue';
import axios from "axios";
import router from '../router'
// Full config: https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.baseURL = 'http://127.0.0.1:9001/'
// axios.interceptors.request.use(config => {
// config.headers.Authorization = window.sessionStorage.getItem('token')
// return config
// })
let config = {
baseURL:'',//这里是请求的请求头
timeout: 60*1000, // Timeout
// withCredentials: true, // Check cross-site Access-Control
};
const _axios = axios.create(config);
Vue.prototype.$http = _axios
_axios.interceptors.request.use(
function (config) {
// Do something before request is sent
const token = window.sessionStorage.getItem('token');
if (token) {
// 设置 token ,一般是在 headers 里加入 Authorization,并加上 Bearer 标注
// 最好通过此种形式设置 request.headers['Authorization']
config.headers['Authorization'] = token; // 基于 nodejs
}
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
// Add a response interceptor
_axios.interceptors.response.use(
function (response) {
// Do something with response data
//console.log(response,'HHHHH')
// loadingInstance.close() // 关闭 loading
if (response.data.token) { // 将返回的最新的 token 保存
window.sessionStorage.setItem('token', response.data.token);
}
return response;
},
function (error) {
console.log(error.response.status, '??')
if (error.response.status === 401) {
// 401 说明 token 验证失败
// 可以直接跳转到登录页面,重新登录获取 token
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);
}
// Do something with response error
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返回的数据
},