关于 axios
面向 JavaScript 和 TypeScript 应用的 Axios 速查技能,涵盖常见请求模式与配置实践,包括拦截器、响应类型和错误处理。
主要功能
- 01GET 与 POST 请求示例
- 02Axios 实例配置
- 03请求与响应拦截器
- 04TypeScript 响应类型
- 05错误处理与问题排查
适用场景
- 01在 JavaScript 或 TypeScript 中调用 API
- 02通过拦截器添加身份验证与错误处理
- 03为特定 API 配置客户端
- 04上传或下载文件
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill axios安装后在 Claude Code 中输入/axios确认已加载。
详细介绍
Axios - 快速参考
何时使用此技能
- 在 JavaScript/TypeScript 应用中发送 HTTP 请求
- 配置拦截器以处理身份验证/错误
- 为特定 API 创建 Axios 实例
- 转换请求/响应
- 上传和下载文件
深入了解:使用
mcp__documentation__fetch_docs,并将技术指定为axios,以获取全面的文档。
基础设置
npm install axios
基本模式
GET 请求
import axios from 'axios';
const response = await axios.get('/api/users');
const users = response.data;
// With params
const response = await axios.get('/api/users', {
params: { page: 1, limit: 10 }
});
POST 请求
const response = await axios.post('/api/users', {
name: 'John',
email: '[email protected]'
});
Axios 实例
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
});
// Use instance
const users = await api.get('/users');
拦截器
// Request interceptor (add auth token)
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor (handle errors)
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Handle unauthorized
window.location.href = '/login';
}
return Promise.reject(error);
}
);
TypeScript 类型
interface User {
id: number;
name: string;
email: string;
}
const response = await api.get<User[]>('/users');
const users: User[] = response.data;
错误处理
try {
const response = await api.get('/users');
} catch (error) {
if (axios.isAxiosError(error)) {
console.error('API Error:', error.response?.data);
console.error('Status:', error.response?.status);
}
}
何时不使用此技能
- 原生 Fetch API 模式(使用
http-clients技能) - ky 或 ofetch 配置(使用
http-clients技能) - GraphQL 客户端设置(使用
graphql-codegen技能) - tRPC 客户端配置(使用
trpc技能) - WebSocket 连接
反模式
| 反模式 | 问题所在 | 解决方案 |
|---|---|---|
| 未配置超时 | 请求会无限期挂起 | 在 axios.create() 中设置超时 |
| 硬编码基础 URL | 与环境耦合 | 使用环境变量设置 baseURL |
| 没有错误拦截器 | 错误处理不一致 | 添加响应错误拦截器 |
| 未为响应指定类型 | 丧失类型安全性 | 使用泛型:axios.get<User>() |
| 重复编写身份验证逻辑 | 增加维护负担 | 使用请求拦截器 |
| 忽略响应状态 | 导致静默失败 | 检查 response.status 或使用 validateStatus |
| 未取消请求 | 卸载时可能导致内存泄漏 | 使用 AbortController |
| 记录敏感数据 | 存在安全风险 | 从日志中删除令牌/密码 |
快速故障排查
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| CORS 错误 | 服务端未允许该来源 | 在服务端配置 CORS,并检查预检请求 |
| 401 未授权 | 缺少令牌或令牌无效 | 检查拦截器并验证令牌 |
| 网络错误 | 服务端不可达或存在 CORS 问题 | 检查 baseURL、服务端状态和 CORS 配置 |
| 超时错误 | 请求耗时过长 | 延长超时时间或优化端点 |
| 请求已取消 | AbortController 已触发 | 检查组件生命周期,不要取消仍需要的请求 |
| 类型错误 | 响应结构不匹配 | 确认 API 响应与类型定义一致 |
| 拦截器未触发 | 在请求发出后才添加拦截器 | 在客户端初始化时添加拦截器 |
| 内存泄漏 | 卸载时未取消请求 | 在 useEffect 中执行清理 |
评论
支持 Markdown