import 'whatwg-fetch' import fetchJsonp from 'fetch-jsonp'; import Cookies from 'universal-cookie'; export const cookies = new Cookies(); export const csrf_token = cookies.get('XSRF-TOKEN'); /* ================= 工具方法 ================== */ /** * 拼接get请求 * @param data * @returns {string} */ export function object2string(o) { const arr = [] for (let i in o) { if (Array.isArray(o[i])) { o[i].forEach((item) => { arr.push(`${i}[]=${item}`) }) } else { arr.push(`${i}=${o[i]}`) } } return arr.join('&') } /** * fetch的get方法封装 * @param path string 请求地址 * @param query object 请求的url参数 * @param options object fetch请求的附加参数 */ export async function get(path: string, query: Object = {}, options: any = {}) { const queryString = object2string(query) if (queryString.length > 0) { path += `?${queryString}` } const response = await fetch(path, { method: 'GET', credentials: 'same-origin', ...options, }) if (!response.ok) { throw new Error(response.status) } let res try { res = await response.json() } catch (err) { throw new Error('服务器错误') } if (res.success === false) { throw new Error(res.msg || '请求失败') } else { // (res.code === -401) && window.location.reload(); return res } } /** * fetch post方法的封装 * @param path string 请求地址 * @param data object 请求的数据 * @param query 请求的url参数 * @param type 请求的数据类型,form/json,默认为form */ export async function post(path: string, data = {}, query = {}, type = 'form', headers = {}) { const isMock = path && path.startsWith('https://nei.hz.netease.com'); const queryString = object2string(query) if (queryString.length > 0) { path += `?${queryString}` } let response; const reqHeaders = isMock ? { 'Content-Type': 'application/x-www-form-urlencoded', ...headers } : { 'Content-Type': 'application/x-www-form-urlencoded', 'X-XSRF-TOKEN': isMock ? null : csrf_token, ...headers } if (type === 'json') { response = await fetch(path, { method: 'POST', credentials: 'same-origin', headers: { ...reqHeaders, 'Content-Type': 'application/json', }, body: JSON.stringify(data) }) } else { response = await fetch(path, { method: 'POST', credentials: 'same-origin', headers: reqHeaders, body: object2string(data) }) } if (!response.ok) { throw new Error(response.status) } let res try { res = await response.json() } catch (err) { throw new Error('服务器错误') } if (res.success === false) { throw new Error(res.msg || '请求失败') } else { // (res.code === -401) && window.location.reload(); return res } } /** * fetch-jsonp的封装 * @param path string 请求地址 * @param query object 请求的url参数 */ export async function jsonp(path:string, query = {}) { const queryString = object2string(query) if (queryString.length > 0) { path += `?${queryString}` } const response = await fetchJsonp(path); if (!response.ok) { throw new Error(response.status) } let res try { res = await response.json() } catch (err) { throw new Error('服务器错误') } if (res.success === false) { throw new Error(res.msg || '请求失败') } else { // (res.code === -401) && window.location.reload(); return res } }