简易版ts+axios封装

用到了VITE变量,可以参考 VITE变量使用方式

import axios, { AxiosRequestConfig } from "axios";

const instance = axios.create({
  baseURL: import.meta.env.VITE_DEVSERVER,
});

// 在 header 中添加本地存储的 token
// 其他操作同理
instance.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["token"] = token;
  }
  // 最后返回 config
  return config;
});

// T 泛型是 Promise 解析出来后 Result 中 data 的结果类型
// 外层是 Result 类型 请自行封装
// 参考
/**
* interface Result {
* 	code: number;
* 	message: string;
* 	data: T;
* }
*/
const http = async <T>(config: AxiosRequestConfig): Promise<Result<T>> => {
  const { data } = await instance.request<Result<T>>(config);
  return data;
};

export default http;

一般使用方式
这里以我写过的 UserAPI 为例
其他同理

import http from "@/utils/http.ts";

export const userLoginAPI = (userLoginVO: UserLoginVO) => {
  return http<string>({
    url: "/user/login",
    method: "POST",
    data: userLoginVO,
  });
};

export const getUserInfoAPI = () => {
  return http<UserVO>({
    url: "/user/info",
    method: "GET",
  });
};

export const updateUserInfoAPI = (userUpdateInfoVO: UserUpdateInfoVO) => {
  return http<string>({
    url: "/user/update",
    method: "PUT",
    data: userUpdateInfoVO,
  });
};

export const userRegisterAPI = (userRegisterVO: UserRegisterVO) => {
  return http<string>({
    url: "/user/register",
    method: "POST",
    data: userRegisterVO,
  });
};

export const userChangePasswordAPI = (userChangePasswordVO: UserChangePasswordVO) => {
  return http<boolean>({
    url: "/user/change_password",
    method: "POST",
    data: userChangePasswordVO,
  });
};

export const userResetPasswordAPI = (userForgetPasswordVO: UserForgetPasswordVO) => {
  return http<string>({
    url: "/user/reset_password",
    method: "PUT",
    data: userForgetPasswordVO,
  });
};

export const checkAdminAPI = () => {
  return http<boolean>({
    url: "/user/check_admin",
    method: "GET",
  });
};

export const uploadAvatarAPI = (formData: FormData) => {
  return http<string>({
    url: "/file/upload_avatar",
    method: "POST",
    data: formData,
  });
};

export const updateAvatarAPI = (avatar: string) => {
  return http<boolean>({
    url: "/user/update_avatar",
    method: "PUT",
    params: {
      avatar,
    },
  });
};

你可能感兴趣的:(typescript)