Axios

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是 Axios?

Axios 是一个基于 TypeScript 编写的流行 HTTP 客户端,适用于浏览器和 Node.js。它提供了便捷且现代化的 API,用于执行异步 HTTP 请求。该库自动处理 JSON 数据,支持拦截器(interceptors)、CSRF 保护和请求取消。

为什么需要 Axios?

与内置的 fetch 不同,Axios 提供了更直观的语法、自动数据转换和内置的错误处理。它非常适合创建 REST API 客户端、处理身份验证和文件上传。得益于 TypeScript 支持,您可以为所有请求和响应获得严格的类型定义。

安装

要在项目中安装 Axios,请使用 npm 或 yarn:

npm install axios# 或者yarn add axios

如需使用 TypeScript,请安装类型定义(通常已包含):

npm install @types/axios

主要功能

  • 支持所有 HTTP 方法: GET、POST、PUT、DELETE、PATCH 等。
  • 自动 JSON 序列化: 数据会自动转换。
  • 拦截器(interceptors): 可以全局处理请求和响应(例如添加令牌)。
  • 请求取消: 使用 CancelToken 或 AbortController。
  • 文件上传: 通过 onUploadProgress 支持上传进度。
  • CSRF 保护: 自动处理 Cookie 和标头。
  • 类型定义: 通过泛型完全支持 TypeScript。

TypeScript 代码示例

带响应类型定义的基本 GET 请求:

import axios, { AxiosResponse } from 'axios';

interface User { id: number; name: string; email: string;}

async function getUser(id: number): Promise<User> { const response: AxiosResponse<User> = await axios.get(`/api/users/${id}`); return response.data;}

// 使用getUser(1).then(user => console.log(user.name));

带数据发送的 POST 请求示例:

import axios from 'axios';

interface CreateUserPayload { name: string; email: string;}

const newUser: CreateUserPayload = { name: 'John', email: 'john@example.com' };

axios.post('/api/users', newUser) .then(response => console.log('User created:', response.data)) .catch(error => console.error('Error:', error));

使用拦截器添加令牌的示例:

import axios from 'axios';

axios.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config;});

何时使用 Axios

Axios 非常适合以下场景:

  • 使用 React、Vue、Angular 或 Svelte 创建客户端应用程序。
  • 需要便捷 HTTP 客户端的 Node.js 服务器。
  • 重视 TypeScript 严格类型定义的项目。
  • 需要拦截器、请求取消或上传进度的场景。

如果您正在使用 fetch 并希望获得更简洁的代码以及自动错误处理,Axios 将是一个绝佳选择。

推荐