import axios from 'axios';import {notification} from 'antd';import {router} from 'umi';import Cookies from 'js-cookie';const codeMessage = { 200: '服务器胜利返回申请的数据。', 201: '新建或批改数据胜利。', 202: '一个申请曾经进入后盾排队(异步工作)。', 204: '删除数据胜利。', 400: '收回的申请有谬误,服务器没有进行新建或批改数据的操作。', 401: '用户没有权限(令牌、用户名、明码谬误)。', 403: '用户失去受权,然而拜访是被禁止的。', 404: '收回的申请针对的是不存在的记录,服务器没有进行操作。', 406: '申请的格局不可得。', 410: '申请的资源被永恒删除,且不会再失去的。', 422: '当创立一个对象时,产生一个验证谬误。', 500: '服务器产生谬误,请查看服务器。', 502: '网关谬误。', 503: '服务不可用,服务器临时过载或保护。', 504: '网关超时。',};function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } const errortext = codeMessage[response.status] || response.statusText; if (response.status !== 401) { notification.error({ message: `申请谬误 ${response.status}: ${response.url}`, description: errortext, }); } const error = new Error(errortext); error.name = response.status; error.response = response; throw error;};// 设置axios的返回拦挡(超时)axios.interceptors.response .use(response => { return response; }, error => { if (error.message.includes('timeout')) { return Promise.reject(error); // reject这个错误信息 } // 判断申请异样信息中是否含有超时timeout字符串 return Promise.reject(error); });export default function request(url, params = {}, method = "get") { try { let token = Cookies.get('Authorization'); if (token) { axios.defaults.headers.common["Authorization"] = JSON.parse(token); } // axios.defaults.headers.common["Cookie"] = ''; } catch (e) { console.error(e) } const options = { // `url` 是用于申请的服务器 URL url: url, // `method` 是创立申请时应用的办法 get 或者 post 是小写 method: method, // `baseURL` 将主动加在 `url` 后面,除非 `url` 是一个相对 URL。 // 它能够通过设置一个 `baseURL` 便于为 axios 实例的办法传递绝对 URL // baseURL: baseURL.baseURL, headers: { 'Content-Type': 'application/json; charset=UTF-8', }, timeout: 6000 }; if (method === "post") { options.data = JSON.stringify(params); } else { options.params = {...params}; } return axios(options) .then(checkStatus) .then(response => response.data) .catch((error) => { if (!Cookies.get('currentHistory')) { Cookies.set('currentHistory', window.location.href); } try { let status = error.response.status; if (status === 401) { window.redirectToLoginPage(); } if (status === 403) { router.push('/exception/403'); return; } if (status <= 504 && status >= 500) { router.push('/exception/500'); return; } if (status >= 404 && status < 422) { router.push('/exception/404'); } } catch { router.push('/exception/404'); } return {code: -500} })}window.request = request;