import axios from 'axios'; // axios.defaults.timeout = 5000; //响应时间 // axios.defaults.withCredentials=true;//让请求头携带参数cookie // axios.defaults.baseURL = ''; //配置接口地址 // axios.defaults.headers.authKey = Lockr.get('authKey'); //接口请求头authKey 按需修改 // axios.defaults.headers.sessionId =Lockr.get('sessionId'); //接口请求头sessionId 按需修改 // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; //配置请求头 import Qs from 'qs' const service = axios.create({ withCredentials: true, crossDomain: true, // baseURL, timeout: 60000 }) //HTTPrequest拦截 service.interceptors.request.use(config => { config.headers['hztToken'] = localStorage.getItem('hztToken') if (config.method === 'post') { if (config.isFormData) { //表单提交 config.headers['Content-Type '] = 'application/x-www-form-urlencoded;charset-utf-8' config.data = Qs.stringify(config.data) } else if (config.isUploadFile) { //文件上传 config.headers['Content-Type'] = 'multipart/form-data' } } return config }, error => { return Promise.reject(error) }); //HTTPresponse拦截 service.interceptors.response.use(response => { switch (response.status) { case 200: return Promise.resolve(response.data) break case 401: toastText = 'token已过期!' break default: uni.hideLoading(); uni.showToast({ title: '加载失败', duration: 1000, icon: 'none' }); return Promise.reject(new Error(response.data || 'Error')) } }, error => { uni.hideLoading(); let toastText = '' if(error.response.data && error.response.data.code){ switch (error.response.data.code) { case 4001: toastText = 'token不能为空,无访问权限!' break case 401: toastText = 'token已过期!' break default: toastText = '加载失败!' } } uni.showToast({ title: toastText, duration: 2000, icon: 'none' }); return Promise.reject(new Error(error)); }) export default service;
标签:axios,封装,data,toastText,error,config,response From: https://www.cnblogs.com/gggjp/p/17103393.html