axios作为vue的ajax请求库使用的是非常普遍,如果我们做一个全局的自定义封装,使用起来就会更方便,

import axios from 'axios';import { Loading } from 'element-ui';import Cookies from 'js-cokie';//基于axios基本配置创建实例const service = axios.create({
timeout: 10*1000
});

// 响应超时时间5s
service.defaults.timeout = 10 * 1000;

// 配置cookie
service.defaults.withCredentials = true;
service.defaults.headers.common['Cookie'] = "xxx"

// 配置post请求头
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

//配置baseurl
service.defaults.baseURL = process.env.DEV_API_ROOT;

let loadingInstance;// 创建http请求拦截器serviece.interceptors.request.use( config => { config.headers['Content-Type'] = 'application/json'; loadingInstance=Loading.serviece({ lock: true, text: '加载中,请稍后...', background: 'rgba(255,255,255,0.7)' }); let token = Cookies.get('jwt-token'); if (token) { config.headers['jwt-token'] = token; } return config; }, err => { return Promise.reject(err); });// 创建http返回拦截器serviece.interceptors.response.use( response => { loadingInstance && loadingInstance.close(); return response.data; }, err => { let { headers,config } =err.response; if (headers['jwt-token']) { Cookies.set('jwt-token', headers['jwt-token'], { expires: 1 /24 }); Cookies.set('token-expires', Date.now(), { expires: 1 /24 }) }; loadingInstance && loadingInstance.close(); return Promise.reject(err); });export default serviece;

以上就是vue自定义封装axios的全部内容,欢迎交流

微信交流