对fetch方法做简单的封装,完成需要统一处理的功能:antd - Table参数映射;取消短时间内的重复请求;options.params参数拼接到url;options.body转换json;headers.Authorization请求头认证赋值;请求异常统一处理;增删改成功提示
import {message} from 'antd'; import _ from '_'; import {cookieUtil} from './util'; const REQUEST_RECORD = {}, DEFAULT_REQUEST_INTERVAL = 1000, DEFAULT_FETCH_OPTIONS = { method: 'GET', mode: 'cors', headers: {}, }, SHOW_MSG_METHOD = { POST: true, PUT: true, DELETE: true, }; /** * Requests a URL, returning a promise. * * @param {string} url The URL we want to request * @param {object} [options] The options we want to pass to "fetch" * @return {object} An object containing either "data" or "err" */ export default function request(url, options = {}) { options = handleTableParams(options); if (!isRepeatedRequest(url, options)) return null; const fetchUrl = generateUrl(url, options); const fetchOptions = generateOptions(options); return fetch(fetchUrl, fetchOptions) .then(checkStatus) .then(parseJSON) .then(data => { if (options['showMsg'] !== false && SHOW_MSG_METHOD[options.method]) { message.success(getMessage(options.method), 2); } return data; }) .catch(() => { return null; }); } function handleTableParams(options) { const params = (options.params = options.params || {}); if (params.pagination) { params.current = options.pagination.current; params.pageSize = options.pagination.pageSize; delete params.pagination; } const filters = params.filters; if (filters) { Object.assign(params, filters); delete params.filters; } if (params.sorter) { const field = params.sorter.field, order = params.sorter.order; if (field && order) params[order] = field; delete params.sorter; } return options; } function isRepeatedRequest(url, options) { let record = REQUEST_RECORD[url], now = new Date().getTime(); if (record && _.isEqual(record.options, options) && now - record.lastTime < DEFAULT_REQUEST_INTERVAL) return false; REQUEST_RECORD[url] = { options: _.assign({}, options), lastTime: now, }; return true; } function generateUrl(url, options) { const params = options.params; if (typeof params === 'object') { let paramArray = []; Object.keys(params).forEach(key => { if (paramArray.length === 0) { paramArray.push('?'); } else { paramArray.push('&'); } paramArray.push(key); paramArray.push('='); paramArray.push(params[key]); }); if (paramArray.length !== 0) { return url + paramArray.join(''); } } return url; } function generateOptions(options) { const fetchOptions = _.assign({}, DEFAULT_FETCH_OPTIONS), method = options.method, data = options.body; options.method = options.method ? options.method.toUpperCase() : 'GET'; if (method) fetchOptions.method = method; if (data && Object.prototype.toString.call(data) === '[object Object]') { fetchOptions.body = JSON.stringify(data); fetchOptions.headers['Content-Type'] = 'application/json'; } const token = cookieUtil.getCookie('token'); if (token) fetchOptions.headers.Authorization = token; return fetchOptions; } function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } else { var error = new Error(response.statusText); response.json().then(data => { message.error(data.message || data, 2); console.error(data); }); throw error; } } function parseJSON(response) { return response.json(); } function getMessage(method) { let sub = ''; switch (method) { case 'POST': sub = '新增成功'; break; case 'PUT': sub = '修改成功'; break; case 'DELETE': sub = '删除成功'; break; default: break; } return sub; }