import axios from 'axios'; import nprogress from 'nprogress'; import { message as MSG } from 'antd'; const baseURL = ''; const service = axios.create({ baseURL, }); // 请求拦截器 service.interceptors.request.use( config => { nprogress.start(); const token = localStorage.getItem('token') || ''; config.headers.token = token; return config; }, error => { error.data = {}; error.data.message = '服务器异常'; MSG.warn('服务器异常!请稍后再试!'); return Promise.resolve(error); } ); // 响应拦截器 service.interceptors.response.use( response => { nprogress.done(); if (response.data.code == 50006) { MSG.warn('请登录再访问!'); setTimeout(() => { window.location.href = '/'; }, 2000); } else if (response.data.code == 50007) { MSG.warn('登录过期,请重新登录!'); setTimeout(() => { window.location.href = '/'; }, 2000); } const status = response.status; let msg = ''; if (status < 200 || status >= 300) { // 处理http错误,抛到业务代码 msg = showStatus(status); if (typeof response.data === 'string') { response.data = { msg }; } else { response.data.msg = msg; } } return response; }, error => { // 错误抛到业务代码 error.data = {}; error.data.msg = '请求超时或服务器异常,请检查网络或联系管理员!'; return Promise.resolve(error); } ); const showStatus = status => { let message = ''; switch (status) { case 400: message = '请求错误(400)'; MSG.warn('请求错误(400)'); break; case 401: message = '未授权,请重新登录(401)'; MSG.warn('未授权,请重新登录(401)'); break; case 403: message = '拒绝访问(403)'; MSG.warn('拒绝访问(403)'); break; case 404: message = '请求出错(404)'; MSG.warn('请求出错(404)'); break; case 408: message = '请求超时(408)'; MSG.warn('请求超时(408)'); break; case 500: message = '服务器错误(500)'; MSG.warn('服务器错误(500'); break; case 501: message = '服务未实现(501)'; MSG.warn('服务未实现(501)'); break; case 502: message = '网络错误(502)'; MSG.warn('网络错误(502)'); break; case 503: message = '服务不可用(503)'; MSG.warn('服务不可用(503)'); break; case 504: message = '网络超时(504)'; MSG.warn('网络超时(504)'); break; case 505: message = 'HTTP版本不受支持(505)'; MSG.warn('HTTP版本不受支持(505)'); break; default: message = `连接出错(${status})!`; MSG.warn(`连接出错(${status})!`); } return `${message},请检查网络或联系管理员!`; }; export default service;
标签:case,break,axios,封装,二次,warn,status,MSG,message From: https://www.cnblogs.com/formerstory/p/16782528.html