1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import fetch from 'dva/fetch’; import { stringify } from 'qs’; import { message } from 'antd’; import { getFormData } from './index’;
export default async function request(url, options) { let newOptions; let newUrl = url; let responseBody = {}; let data = {}; const { body, params } = options; if ((!(typeof body === 'string')) && body) { newOptions = Object.assign({}, options, { body: getFormData(body) }); responseBody = { credentials: 'same-origin', ...newOptions, }; } else { newOptions = options; responseBody = { credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, ...newOptions, }; } if (params) { newUrl += `?${stringify(params)}`; } const response = await fetch(newUrl, responseBody); if (response.headers.get('Content-Type').indexOf('application/msexcel') > -1) { response.blob().then((blob) => { const a = window.document.createElement('a'); const downUrl = window.URL.createObjectURL(blob); const filename = response.headers.get('Content-Disposition').split('filename=')[1].split('.'); a.href = downUrl; a.download = `${decodeURI(filename[0])}.${filename[1]}`; a.click(); window.URL.revokeObjectURL(downUrl); }); return data; } if (response.status !== 200) { message.error('网络或服务器异常!'); return { data: { code: response.status, }, }; } data = await response.json(); if (data.code !== '200') { if (data.code !== '304' && data.code !== '302') { console.log(data.msg); message.error(data.msg); } if (data.code === '304') { request('/login', { method: 'post', body: { ...data.data, redirect_uri: encodeURIComponent(window.location.href), }, }); } if (data.code === '302') { window.location = data.msg; } } return { data }; }
|