Skip to content

Fetch封装 ​

javascript
import { notification } from "antd";
import { BaseApiResponse } from "@/utils/fetchExt";
import { getCookie } from "./cookie";
import queryString from "query-string";

// 获取身份令牌
export function getAuthorization() {
  const AccessTokenAdmin = getCookie("access_token");
  if (AccessTokenAdmin) {
    return {
      Authorization: `Bearer ${AccessTokenAdmin}`,
    };
  }

  return undefined;
}
// 用来处理网络请求 status
// http status
export async function resposneStateHandler(response: Response) {
  const { status, statusText } = response;
  const releaseArr = [200, 304, 201];
  if (releaseArr.includes(status)) {
    return Promise.resolve(response);
  } else {
    console.warn("报错了", statusText);
  }

  // if (status === -100 || status === 401) {
  //   setTimeout(() => {
  //     cookie.remove("access_token_admin");
  //     // window.localStorage.clear();
  //     const urlObj = new URL(window.location.href);
  //     if (urlObj?.pathname !== "/login") {
  //       window.location.replace("/login");
  //     }
  //   }, 1000);
  //   return;
  // }
  // if (status === 403) {
  // } else if (status === 404) {
  //   // window.location.replace('/404');
  // } else if (status >= 500 && status < 600) {
  //   // window.location.replace('/500');
  // }

  // let errText = statusText;

  // try {
  //   const res = (await response.json()) as BaseApiResponse;
  //   errText = res.message || errText;
  // } catch (error) {
  //   // ignore this useless error
  // }

  // const description = `[${status}]:${errText}`;
  //   notification.error({
  //     message: t("CommonMessage.Systemerror"),
  //     description,
  //   });

  return Promise.reject(response);
}

// 用来处理resposne body中的 code
function responseCodeHandler<T>(
  response: BaseApiResponse<T>
): Promise<BaseApiResponse<T>> {
  const code = response.code || 0;
  let message = response.message;
  const codeArr = [0, 200];
  if (codeArr.includes(Number(code))) {
    return Promise.resolve(response);
  }
  const description = `[${code}]:${message}`;
  notification.error({
    message,
    description,
  });
  return Promise.reject(response);
}

// 请求处理函数
function responseHandle<T>(response: Response) {
  return Promise.resolve(response)
    .then((res) => resposneStateHandler(res))
    .then((res) => res?.json())
    .then((res) => responseCodeHandler<T>(res));
}

export async function get<T>(
  url: string,
  data?: { [key: string]: unknown }
): Promise<BaseApiResponse<T>> {
  const locationSearch = data && queryString.stringify(data);
  const finUrl = locationSearch ? `${url}?${locationSearch}` : url;
  return fetch(finUrl, {
    headers: {
      "Content-Type": "application/json",
      ...getAuthorization(),
    },
  })
    .then((response) => responseHandle<T>(response))
    .catch((ex) => Promise.reject(ex));
}

//post请求
export function post<T>(Url: string, data?: any): Promise<BaseApiResponse<T>> {
  return fetch(Url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...getAuthorization(),
    },
    body: typeof data === "string" ? data : JSON.stringify(data),
  })
    .then((response) => responseHandle<T>(response))
    .catch((ex) => Promise.reject(ex));
}

//put请求
export async function put<T>(
  url: string,
  body: any
): Promise<BaseApiResponse<T>> {
  const response = await fetch(url, {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
      ...getAuthorization(),
    },
    body: JSON.stringify(body),
  });
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  const data = await response.json();
  return data;
}
//delete请求
export async function delet<T>(
  url: string,
  data?: any
): Promise<BaseApiResponse<T>> {
  const response = await fetch(url, {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json",
      ...getAuthorization(),
    },
    body: JSON.stringify(data),
  });
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  const res = await response.json();
  return res;
}
javascript
export function getCookie(key: string) {
  return localStorage.getItem(key);
}
export function setCookie(key: string, value: string) {
  localStorage.setItem(key, value);
}

使用方法

javascript

T是泛型
export async function getAllLives(id?: string) {
  const res = id ? `?id=${id}` : "";
  return get<T>(FetchAPIPath.GetAllLives + res);
}

//调用时,使用try...catch
async function getData() {
    try {
      const res = await getAllLives();
      if (res.code === 200) {
        setData(res.result);
      }
    } catch (error) {
      console.warn(error);
    }
  }