You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.3 KiB

  1. type HttpReqParam = {
  2. url: string;
  3. method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
  4. params?: Record<string, any>;
  5. encode?: "form" | "json"; // 入参编码类型
  6. headers?: Record<string, any>;
  7. };
  8. export default async function httpRequest<T>({ url, method = "GET", params = {}, encode = "json", headers = {} }: HttpReqParam) {
  9. // const token = sessionStorage.getItem("token");
  10. // if (token) {
  11. // headers = { Authorization: token, ...headers };
  12. // }
  13. if (method === "GET") {
  14. const query = urlEncode(params);
  15. const _url = query ? url + "?" + query : url;
  16. const res = await fetch(_url, { headers });
  17. return res.json() as Promise<T>;
  18. } else {
  19. const body = encode === "json" ? JSON.stringify(params) : urlEncode(params);
  20. const _headers =
  21. encode === "json"
  22. ? { "Content-Type": "application/json; charset=utf-8", ...headers }
  23. : { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", ...headers };
  24. const res = await fetch(url, { method, headers: _headers, body });
  25. return res.json() as Promise<T>;
  26. }
  27. }
  28. export function urlEncode(params?: Record<string, any>) {
  29. let query = "";
  30. if (params && Object.keys(params).length > 0) {
  31. const qs = [];
  32. for (let attr in params) {
  33. qs.push(`${attr}=${encodeURIComponent(params[attr])}`);
  34. }
  35. query = qs.join("&");
  36. }
  37. return query;
  38. }