axios
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAxios - Quick Reference
Axios - 快速参考
When to Use This Skill
何时使用该技能
- HTTP requests in JavaScript/TypeScript applications
- Configuring interceptors for auth/error handling
- Creating Axios instances for specific APIs
- Request/response transformation
- File uploads and downloads
Deep Knowledge: Usewith technology:mcp__documentation__fetch_docsfor comprehensive documentation.axios
- JavaScript/TypeScript应用中的HTTP请求
- 配置用于认证/错误处理的拦截器
- 为特定API创建Axios实例
- 请求/响应转换
- 文件上传与下载
深度知识:使用并指定技术为mcp__documentation__fetch_docs以获取完整文档。axios
Setup Base
基础设置
bash
npm install axiosbash
npm install axiosPattern Essenziali
核心模式
GET Request
GET请求
typescript
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 }
});typescript
import axios from 'axios';
const response = await axios.get('/api/users');
const users = response.data;
// 带参数
const response = await axios.get('/api/users', {
params: { page: 1, limit: 10 }
});POST Request
POST请求
typescript
const response = await axios.post('/api/users', {
name: 'John',
email: 'john@example.com'
});typescript
const response = await axios.post('/api/users', {
name: 'John',
email: 'john@example.com'
});Axios Instance
Axios实例
typescript
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
});
// Use instance
const users = await api.get('/users');typescript
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
});
// 使用实例
const users = await api.get('/users');Interceptors
拦截器
typescript
// 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
// 请求拦截器(添加认证令牌)
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// 响应拦截器(处理错误)
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// 处理未授权情况
window.location.href = '/login';
}
return Promise.reject(error);
}
);TypeScript Types
TypeScript类型
typescript
interface User {
id: number;
name: string;
email: string;
}
const response = await api.get<User[]>('/users');
const users: User[] = response.data;typescript
interface User {
id: number;
name: string;
email: string;
}
const response = await api.get<User[]>('/users');
const users: User[] = response.data;Error Handling
错误处理
typescript
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);
}
}typescript
try {
const response = await api.get('/users');
} catch (error) {
if (axios.isAxiosError(error)) {
console.error('API错误:', error.response?.data);
console.error('状态码:', error.response?.status);
}
}When NOT to Use This Skill
何时不使用该技能
- Native Fetch API patterns (use skill)
http-clients - ky or ofetch configuration (use skill)
http-clients - GraphQL client setup (use skill)
graphql-codegen - tRPC client configuration (use skill)
trpc - WebSocket connections
- 原生Fetch API相关场景(请使用技能)
http-clients - ky或ofetch配置(请使用技能)
http-clients - GraphQL客户端设置(请使用技能)
graphql-codegen - tRPC客户端配置(请使用技能)
trpc - WebSocket连接
Anti-Patterns
反模式
| Anti-Pattern | Why It's Bad | Solution |
|---|---|---|
| No timeout configured | Requests hang indefinitely | Set timeout in axios.create() |
| Hardcoded base URLs | Environment coupling | Use env variables for baseURL |
| No error interceptor | Inconsistent error handling | Add response error interceptor |
| Not typing responses | Loses type safety | Use generics: |
| Duplicating auth logic | Maintenance burden | Use request interceptor |
| Ignoring response status | Silent failures | Check response.status or use validateStatus |
| No request cancellation | Memory leaks on unmount | Use AbortController |
| Logging sensitive data | Security risk | Redact tokens/passwords from logs |
| 反模式 | 问题所在 | 解决方案 |
|---|---|---|
| 未配置超时 | 请求会无限挂起 | 在axios.create()中设置timeout |
| 硬编码基础URL | 与环境耦合 | 使用环境变量设置baseURL |
| 未添加错误拦截器 | 错误处理不一致 | 添加响应错误拦截器 |
| 不对响应进行类型定义 | 失去类型安全性 | 使用泛型: |
| 重复编写认证逻辑 | 维护负担重 | 使用请求拦截器 |
| 忽略响应状态码 | 静默失败 | 检查response.status或使用validateStatus |
| 未取消请求 | 组件卸载时内存泄漏 | 使用AbortController |
| 记录敏感数据 | 安全风险 | 在日志中屏蔽令牌/密码等敏感信息 |
Quick Troubleshooting
快速故障排除
| Issue | Possible Cause | Solution |
|---|---|---|
| CORS errors | Server not allowing origin | Configure CORS on server, check preflight |
| 401 Unauthorized | Missing or invalid token | Check interceptor, verify token |
| Network Error | Server unreachable, CORS | Check baseURL, server status, CORS config |
| Timeout errors | Request taking too long | Increase timeout or optimize endpoint |
| Request canceled | AbortController triggered | Check component lifecycle, don't cancel needed requests |
| Type errors | Response shape mismatch | Verify API response matches type definition |
| Interceptor not firing | Interceptor added after request | Add interceptors during client setup |
| Memory leaks | Not canceling requests on unmount | Use cleanup in useEffect |
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| CORS错误 | 服务器不允许当前源 | 在服务器上配置CORS,检查预检请求 |
| 401未授权 | 令牌缺失或无效 | 检查拦截器,验证令牌有效性 |
| 网络错误 | 服务器不可达、CORS问题 | 检查baseURL、服务器状态、CORS配置 |
| 超时错误 | 请求耗时过长 | 增加超时时间或优化接口 |
| 请求被取消 | AbortController被触发 | 检查组件生命周期,不要取消必要的请求 |
| 类型错误 | 响应结构不匹配 | 验证API响应是否符合类型定义 |
| 拦截器未触发 | 拦截器在请求之后添加 | 在客户端初始化时添加拦截器 |
| 内存泄漏 | 组件卸载时未取消请求 | 在useEffect中添加清理逻辑 |