小纸条1号
小纸条1号
发布于 2025-09-22 / 0 阅读
0

vue3 二次封装axios

import type { IApiResult } from "@/api/type";
import axios from "axios";
import { ElNotification } from "element-plus";

//创建axios对象
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || "", //基础url
  timeout: 10000, //超时时间
  withCredentials: true, //
  headers: {
    //请求头设置
    "Content-Type": "application/json;charset=UTF-8",
  },
});

//设置全局请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    //错误提示框,使用element-plus ElNotification组件
    ElNotification({
      type: "error",
      title: "错误提示",
      message: error,
      duration: 3000,
    });
    return Promise.reject(error);
  },
);

//响应拦截器,全局处理返回值,采用后端返回的message信息
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code != 200) {
      ElNotification({
        type: "error",
        title: "错误提示",
        message: res.message,
        duration: 3000,
      });
      if (res.code === 401) {
        ElNotification({
          type: "error",
          title: "错误提示",
          message: res.message,
          duration: 3000,
        });
        localStorage.removeItem("token");
        window.location.href = "/login";
      }
      return Promise.reject(res);
    }
    return res;
  },
  (error) => {
    ElNotification({
      type: "error",
      title: "错误提示",
      message: "系统内部错误",
      duration: 3000,
    });
    return Promise.reject(error);
  },
);

//封装方法
const request = {
  get<T>(url: string, params = {}, config = {}): Promise<IApiResult<T>> {
    return service.get(url, { params, ...config });
  },
  post<T>(url: string, data = {}, config = {}): Promise<IApiResult<T>> {
    return service.post(url, data, config);
  },
};

//暴露请求对象
export default request;

请求返回值对象types.ts

//请求响应参数
export type IApiResult<T = any> = {
  code: number;
  message: string;
  data?: T;
};