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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| const TIME_OUT = 6000; const TOKEN = 'token'; const ContentType = { json:'application/json;charset=UTF-8', form: 'application/x-www-form-urlencoded; charset=UTF-8', download: 'application/octet-stream' };
function baseFetch(url, options) {
const baseOptions = { method: "GET", headers: { "Content-type": ContentType.json },
credentials: 'include' };
options = Object.assign(baseOptions, options);
const {method, body} = options;
if (method === 'GET' && Object.isObject(body)) { const paramsArray = []; Object.keys(body).forEach((key) => paramsArray.push(key + "=" + encodeURIComponent(body[key])) ); if (url.search(/\?/) === -1) { url += "?" + paramsArray.join("&"); } else { url += "&" + paramsArray.join("&"); }
delete options.body; }
const token = localStorage.getItem(TOKEN); if (token) options.headers["TOKEN"] = token;
return Promise.race([ new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('request timeout')); }, TIME_OUT); }), new Promise((resolve, reject) => { window.fetch(url, options) .then(async res => {
if(!/^(2|3)\d{2}$/.test(res.status)) { switch(res.status) { case 401: break case 403: localStorage.removeItem(TOKEN) break case 404: break } return Promise.reject(res) } if (res.headers['set-cookies']) { localStorage.setItem(TOKEN, res.headers['set-cookies']); }
const data = options.headers['Content-type'] === ContentType.download ? res.blob() : res.json(); resolve(data); }) .catch(err => { reject(err); }); }) ]) }
export const fetchGet = (url, params) => { return baseFetch(url, {body: params}); }
export const fetchPost = (url, params) => { return baseFetch(url, {method: 'POST', body: JSON.stringify(params)}); }
export const fetchDownload = (url, params) => { return baseFetch(url, { method: 'POST', body: JSON.stringify(params), headers: { "Content-type": ContentType.download } }); }
|