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
| function request(option = { method: 'GET', formData: false }) { let url = option.url if (option.param) { url = `${url}?${qs(option.param)}` } function qs(data, flag) { const typeObj = (obj) => Object.prototype.toString.call(obj).slice(8, -1) === 'Object' const typeArr = (obj) => Object.prototype.toString.call(obj).slice(8, -1) === 'Array' var str = '', originData, encodeData; for (var i in data) { if (data.hasOwnProperty(i)) { originData = data[i] if (typeObj(originData) || typeArr(originData)) { str += qs(originData, i) } else { encodeData = encodeURIComponent(originData) if (typeObj(data) && flag) { str += `${flag}[${i}]=${encodeData}&` } else if (typeArr(data) && flag) { str += `${flag}[${i}]=${encodeData}&` } else { if (str.length > 0 && str[str.length - 1] !== '&') str += '&'; str += `${i}=${encodeData}&` } } } } return str[str.length - 1] === '&' ? str.slice(0, -1) : str } return fetch(url, { method: option.method, headers: option.formData ? undefined : { 'Content-Type': 'application/json', }, body: option.formData ? Object.keys(option.data).reduce((ret, val) => { ret.append(val, option.data[val]) return ret }, new FormData()) : JSON.stringify(option.data), }).then(response => response.json()) }
|