Axios使用

配置Axios响应拦截器

为了配置 Axios 直接返回 response.data,可以使用 Axios 的响应拦截器。这样,每次请求时,你的代码只会处理响应数据,而不是整个响应对象。

下面是如何配置 Axios 拦截器来实现这一点的步骤:

  1. 创建 Axios 实例并配置拦截器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import axios, { AxiosResponse } from 'axios';

// 创建 Axios 实例
const axiosInstance = axios.create(
    // 实例默认值
    {
        baseURL: 'http://your-api-base-url',
        timeout: 10000,
        headers: { 'Content-Type': 'application/json' },
    }
);

// 配置响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => response.data,
  (error) => {
    // 处理错误
    return Promise.reject(error);
  }
);

// 导出 Axios 实例
export default axiosInstance;
  1. 使用配置好的 Axios 实例进行请求
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import axiosInstance from './path-to-your-axios-instance';

interface UserProfileDTO {
  roles: string[];
  permissions: string[];
}

interface UserProfileRequestParams {
  userId: string;
}

export const getUserProfile = (params: UserProfileRequestParams): Promise<UserProfileDTO> => {
  return axiosInstance.get<UserProfileDTO>("/system/v1/user/profile", { params });
};

// 调用请求函数
const fetchUserProfile = async () => {
  try {
    const data = await getUserProfile({ userId: '12345' });
    console.log("User Profile:", data);
    const { roles, permissions } = data;
    console.log("Roles:", roles);
    console.log("Permissions:", permissions);
  } catch (error) {
    console.error("Error fetching user profile:", error);
  }
};

// 执行函数
fetchUserProfile();

解释

  1. 创建 Axios 实例

    • 使用 axios.create 方法创建一个 Axios 实例,并配置基础 URL、超时和默认头部。
  2. 配置响应拦截器

    • 使用 axiosInstance.interceptors.response.use 方法添加一个响应拦截器。
    • 在拦截器中,将 response.data 返回,从而使所有通过该实例进行的请求都只返回数据部分。
  3. 导出配置好的 Axios 实例

    • 将配置好的 Axios 实例导出,以便在其他地方使用。
  4. 使用 Axios 实例进行请求

    • 在请求函数 getUserProfile 中,使用配置好的 Axios 实例进行请求。
    • 因为拦截器已经处理了响应对象,所以 getUserProfile 直接返回 response.data
  5. 调用和处理请求

    • fetchUserProfile 函数中调用 getUserProfile,并直接获取数据部分。
    • 处理并使用响应数据。

指定入参 & 响应数据类型

在使用 Axios 进行 HTTP 请求时,可以通过泛型来指定请求参数和响应数据的类型。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计