/** * request 网络请求工具 */ import { extend } from 'umi-request'; import { notification, message } from 'antd'; const codeMessage: any = { 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content', 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'File Not Found', 406: 'Not Acceptable', 410: 'Gone', 422: 'Unprocessable Entity', 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', }; /** * 异常处理程序 */ const errorHandler = (error: any) => { let { response } = error; response = response || {}; const errortext = codeMessage[response.status] || response.statusText; const { status, url } = response; if (status === 401 || status === 403) { return; } notification.destroy(); notification.error({ message: `error ${status}: ${url}`, description: errortext, }); }; /** * 配置request请求时的默认参数 */ const request = extend({ errorHandler, // 默认错误处理 prefix: '/adminApi', // prefix headers: { 'Content-Type': 'application/json', authorization: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJkZXBhcnRtZW50TmFtZVwiOlwi6Im65Lq66L-Q6JCl57q_XCIsXCJkYXRlXCI6MTU5MDkwODg1NzI0NyxcImdlbmRlclwiOjAsXCJ1c2VyUmVhbE5hbWVcIjpcIuecn-WQjWhhaTU5OTNcIixcImF2YXRhclwiOlwiaHR0cHM6Ly9hdHRhY2htZW50LXRlc3QubXR0b3AuY24vNmQ0ZTIxYmItZDkyYS00ZDRhLTk0YTUtMzQwMmViMWVjMzgwLmpwZ1wiLFwidXNlck5hbWVcIjpcIuiKseWQjWNoYWk4ODIzXCIsXCJkZXBhcnRtZXRuSWRcIjoyLFwidXNlcklkXCI6NDc5fSIsImlzcyI6ImF1dGgxIiwiZXhwIjoxNTkxMTY4MDU3LCJ1dWlkIjoiNGVmMmY2MjItOGFjZS00NDdhLWIwYjAtZjVkNGQxMjJiNTM4In0.6RlLBnX74MG83E-WYBmFylCluPBTStUWOZNcRfz7xf4', }, // credentials: 'omit', // 默认请求是否带上cookie,暂不做处理,如需添加请设置跨域处进行设置 }); // 动态添加数据; request.interceptors.request.use((url, options: any) => { options.headers = { ...options.headers }; return { url, options, }; }); // 处理异常数据 request.interceptors.response.use(async (response, ops: any) => { if (response.status === 200) { const data = await response.clone().json(); if (!data.success) { message.config({ maxCount: 1, }); message.error(data.message || data.msg); } } return response; }); export default request;