Configs2026年4月11日·1 分钟阅读

axios — Promise-Based HTTP Client for Browser & Node.js

axios is the most popular HTTP client for JavaScript — promise-based, isomorphic (browser + Node), with request/response interceptors, automatic JSON transforms, CSRF protection, and built-in cancellation. Battle-tested since 2014.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

npm i axios
import axios from "axios";

// GET
const { data } = await axios.get("https://api.github.com/users/williamwangai");

// POST with JSON body
await axios.post("/api/users", { name: "William", email: "w@example.com" });

// Create instance with defaults
const api = axios.create({
  baseURL: "https://api.tokrepo.com",
  headers: { Authorization: `Bearer ${token}` },
  timeout: 10000,
});

api.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response?.status === 401) location.href = "/login";
    return Promise.reject(err);
  }
);
介绍

axios is the most popular HTTP client for JavaScript — promise-based, isomorphic (works in browser and Node.js with the same API), battle-tested since 2014. Despite the modern fetch() API being available everywhere, axios still ships in 100M+ weekly npm installs for its superior DX.

What axios Does

  • Promise API — async/await friendly
  • Isomorphic — same code browser + Node.js
  • Interceptors — transform requests/responses globally
  • Auto JSON — serializes request body, parses response
  • Timeoutstimeout option
  • CancellationAbortController support
  • Progress events — upload/download progress
  • XSRF protection — cookie-based CSRF token
  • Instance configaxios.create({ baseURL, headers })

Architecture

Wraps XMLHttpRequest in browsers and http/https modules in Node.js. Request goes through interceptor chain → adapter → transformer → promise. Error is a normal rejected promise with err.response/err.request for inspection.

Self-Hosting

Client library only.

Key Features

  • Isomorphic (browser + Node)
  • Request/response interceptors
  • Automatic JSON transforms
  • Form data & multipart support
  • Streaming in Node.js
  • Cancellation via AbortController
  • Progress events (uploads)
  • TypeScript types built in
  • AbortController and signal support

Comparison

Client Isomorphic Interceptors Auto JSON Bundle
axios Yes Yes Yes ~14KB
fetch Yes (modern) No (manual) No (manual) 0
ky Yes (modern) Yes Yes ~5KB
ofetch Yes Limited Yes ~4KB
got Node only Yes Yes ~40KB

常见问题 FAQ

Q: fetch 已经够用了,为什么还要 axios? A: fetch 不自动 JSON parse、不自动 throw HTTP 错误、没有 interceptors、Node 老版本不支持。axios 开箱即用省时。

Q: 如何取消请求? A: const controller = new AbortController(); axios.get(url, { signal: controller.signal }); controller.abort();

Q: 怎么处理 CSRF? A: axios 默认读 XSRF-TOKEN cookie 并放到 X-XSRF-TOKEN header,配合 Rails/Laravel 的 CSRF 机制。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产