import { notification } from 'antd'; import HttpRequest from './kim-request'; import config from '@/config'; const { baseUrl, apiPrefix, headers } = config; /** * 异常处理程序 */ const errorHandler = error => { const { response } = error; if (response && response.status) { const errorText = response.statusText; const { status, url, code } = response; notification.error({ key: `notification_${code}`, message: `请求错误 ${status}: ${url}`, description: errorText, }); } }; const axios = new HttpRequest({ baseUrl, headers: headers() || {}, errorHandler, }); const mergeApi = (url, more) => { if (more && more.apiPrefix && typeof more.apiPrefix === 'string') { return `${config.apiPrefix}${url}`; } if (apiPrefix && typeof apiPrefix === 'string') { return `${config.apiPrefix}${url}`; } return url; }; const get = (url, data, more = {}) => axios.request({ method: 'get', // default url: `${mergeApi(url, more)}`, params: data, ...more, }); const post = (url, data, more = {}) => axios.request({ method: 'post', // default url: `${mergeApi(url, more)}`, data, ...more, }); const put = (url, data, more = {}) => axios.request({ method: 'put', // default url: `${mergeApi(url, more)}`, data, ...more, }); const del = (url, data, more = {}) => axios.request({ method: 'delete', // default url: `${mergeApi(url, more)}`, data, ...more, }); const patch = (url, data, more = {}) => axios.request({ method: 'patch', // default url: `${mergeApi(url, more)}`, data, ...more, }); const formDataUpload = (url, data, more = {}) => { const formData = new FormData(); if (data) { Object.keys(data).forEach(key => { formData.append(key, data[key]); }); } axios.request({ method: 'post', // default url: `${mergeApi(url, more)}`, data: formData, headers: { 'Content-Type': 'multipart/form-data', }, ...more, }); }; const uploadFile = (url, data, type = 'formData', more = {}) => { if (type === 'formData') { formDataUpload(url, data, more); } }; export { axios as request, get, post, put, del, patch, uploadFile };