vue使用axios封装接口的请求(完整详细的项目封装和接口使用过程,附有axios的ts源码)

本文详细介绍了如何在Vue项目中使用axios进行API请求的封装,并展示了如何在request.js中设置请求拦截器和响应拦截器,以及在api.js和demo.vue页面中实际调用封装后的接口。还附带了axios的基础类型定义和接口实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//使用 "axios"封装一下请求的接口 vue项目为例

第一部分:request.js内容:

//引入axios
import axios from "axios";
import Cookies from "js-cookie";
const service = axios.create({
    baseURL: process.env.MY_PROJECT_URL, // api 的 base_url  也就是代表各个环境 比如dev test 等
    timeout: 10000  //默认全部接口的请求的时间
});
// 请求时的拦截器
service.interceptors.request.use(
    config => {
      //请求的处理 比如处理请求头和TOKEN等等
        config.headers.Authorization = Cookies.get("access_token") || "";
        config.headers.APP_TOKEN = localStorage.appToken || "";
       //处理完允许往下执行请求
        return config;
    },
    error => {
       //报错请求抛异常信息
        Promise.reject(error);
    }
);

// 响应时的拦截器
service.interceptors.response.use(
    response => {
        // 后端报错处理
        if (response.data.code !== "0") {
           //一般这里处理的是接口请求报错的各种情况 -- 根据情况自己处理
        } else {
            // 请求正常
            return response;
        }
    },
    error => {
        // 系统错误处理  自己根据情况处理 
        return Promise.reject(error);
    }
);
export default service;

第二部分:
以下是使用request.js的处理接口的请求,也就是在api.js中的内容如下:

import request from "@/request";
//这块是后端给的接口url:/apis/demo/app/homePage  只是例子 根据自己项目url不同修改
export  const homePage= (obj)=> {
  return request({
    url: "/apis/demo/app/homePage",
    method: "post",
    data: obj,
     // 单个接口设置请求时间
    timeout: 1000
  });
}

第三部分:项目页面可以直接的测试封装接口的使用 demo.vue页面为例

<template>
  <div></div>
</template>
<script>
import { homePage } from "@/apis/api.js";

export default {
  name: "demo",
  data() {
    return {
      data: [],
    };
  },
  created() {
    this.demoData();
  },
  methods: {
    //获取getUserList 接口数据
    demoData() {
      homePage(obj)
        .then((res) => {
          //接口请求成功逻辑处理
          this.data = res.data.data;
          console.log(res);
        })
        .catch((e) => {
          //接口异常信息
          console.log(e);
        });
    },
  },
};
</script>

第四部分 axios ts源码
index.d.ts文件代码如下:

export interface AxiosTransformer {
  (data: any, headers?: any): any;
}

export interface AxiosAdapter {
  (config: AxiosRequestConfig): AxiosPromise<any>;
}

export interface AxiosBasicCredentials {
  username: string;
  password: string;
}

export interface AxiosProxyConfig {
  host: string;
  port: number;
  auth?: {
    username: string;
    password:string;
  };
  protocol?: string;
}

export type Method =
  | 'get' | 'GET'
  | 'delete' | 'DELETE'
  | 'head' | 'HEAD'
  | 'options' | 'OPTIONS'
  | 'post' | 'POST'
  | 'put' | 'PUT'
  | 'patch' | 'PATCH'
  | 'link' | 'LINK'
  | 'unlink' | 'UNLINK'

export type ResponseType = 
  | 'arraybuffer' 
  | 'blob' 
  | 'document' 
  | 'json' 
  | 'text' 
  | 'stream'

export interface AxiosRequestConfig {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  transformResponse?: AxiosTransformer | AxiosTransformer[];
  headers?: any;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: any;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: (status: number) => boolean;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
}

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

export interface AxiosError<T = any> extends Error {
  config: AxiosRequestConfig;
  code?: string;
  request?: any;
  response?: AxiosResponse<T>;
  isAxiosError: boolean;
  toJSON: () => object;
}

export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
}

export interface CancelStatic {
  new (message?: string): Cancel;
}

export interface Cancel {
  message: string;
}

export interface Canceler {
  (message?: string): void;
}

export interface CancelTokenStatic {
  new (executor: (cancel: Canceler) => void): CancelToken;
  source(): CancelTokenSource;
}

export interface CancelToken {
  promise: Promise<Cancel>;
  reason?: Cancel;
  throwIfRequested(): void;
}

export interface CancelTokenSource {
  token: CancelToken;
  cancel: Canceler;
}

export interface AxiosInterceptorManager<V> {
  use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
  eject(id: number): void;
}

export interface AxiosInstance {
  (config: AxiosRequestConfig): AxiosPromise;
  (url: string, config?: AxiosRequestConfig): AxiosPromise;
  defaults: AxiosRequestConfig;
  interceptors: {
    request: AxiosInterceptorManager<AxiosRequestConfig>;
    response: AxiosInterceptorManager<AxiosResponse>;
  };
  getUri(config?: AxiosRequestConfig): string;
  request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
  get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
}

export interface AxiosStatic extends AxiosInstance {
  create(config?: AxiosRequestConfig): AxiosInstance;
  Cancel: CancelStatic;
  CancelToken: CancelTokenStatic;
  isCancel(value: any): boolean;
  all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}

declare const Axios: AxiosStatic;

export default Axios;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追逐梦想之路_随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值