type HttpReqParam = { url: string; method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; params?: Record; encode?: "form" | "json"; // 入参编码类型 headers?: Record; }; export default async function httpRequest({ url, method = "GET", params = {}, encode = "json", headers = {} }: HttpReqParam) { // const token = sessionStorage.getItem("token"); // if (token) { // headers = { Authorization: token, ...headers }; // } if (method === "GET") { const query = urlEncode(params); const _url = query ? url + "?" + query : url; const res = await fetch(_url, { headers }); return res.json() as Promise; } else { const body = encode === "json" ? JSON.stringify(params) : urlEncode(params); const _headers = encode === "json" ? { "Content-Type": "application/json; charset=utf-8", ...headers } : { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", ...headers }; const res = await fetch(url, { method, headers: _headers, body }); return res.json() as Promise; } } export function urlEncode(params?: Record) { let query = ""; if (params && Object.keys(params).length > 0) { const qs = []; for (let attr in params) { qs.push(`${attr}=${encodeURIComponent(params[attr])}`); } query = qs.join("&"); } return query; }