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, }); } }; /** * 组装url * @param {url} url * @param {配置参数} more */ 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 axios = new HttpRequest({ baseUrl, headers: headers() || {}, errorHandler, }); /** * 正常返回结果处理 * @param {返回请求数据} response * @param {配置项} more */ const checkCode = (response, more) => {}; export default function request(url, options = {}, more = {}) { let newOptions = options; newOptions.url = url; if (more.headers) { newOptions = { ...options, headers: more.headers }; } return axios.request(newOptions).then(response => checkCode(response, more)); } const get = (url, data, more = {}) => request( `${mergeApi(url, more)}`, { method: 'get', // default params: data, }, more, ); const post = (url, data, more = {}) => request( `${mergeApi(url, more)}`, { method: 'post', // default data, }, more, ); const put = (url, data, more = {}) => request( `${mergeApi(url, more)}`, { method: 'put', // default data, }, more, ); const del = (url, data, more = {}) => request( `${mergeApi(url, more)}`, { method: 'delete', // default data, }, more, ); const patch = (url, data, more = {}) => request( `${mergeApi(url, more)}`, { method: 'patch', // default data, ...more, }, more, ); const formDataUpload = (url, data, more = {}) => { const formData = new FormData(); if (data) { Object.keys(data).forEach(key => { formData.append(key, data[key]); }); } post(`${mergeApi(url, more)}`, formData, { headers: { 'Content-Type': 'multipart/form-data', }, ...more, }); }; const uploadFile = (url, data, type = 'formData', more = {}) => { if (type === 'formData') { formDataUpload(url, data, more); } }; export { request, get, post, put, del, patch, uploadFile };