关于 axios
Axios 是面向浏览器和 Node.js 应用的基于 Promise 的 HTTP 客户端,提供请求与响应 API,并支持配置、拦截器和错误处理。
主要功能
- 01基于 Promise 的 HTTP 请求
- 02支持浏览器和 Node.js
- 03自定义实例与配置
- 04请求和响应拦截器
- 05跟踪上传和下载进度
适用场景
- 01发送 GET 和 POST 请求
- 02配置面向不同 API 的客户端
- 03通过拦截器添加身份验证
- 04跟踪文件上传或下载进度
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ slanycukr/ riot-api-project --skill axios安装后在 Claude Code 中输入/axios确认已加载。
详细介绍
Axios HTTP 客户端
Axios 是一款基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。它提供了简洁的 API,用于发送 HTTP 请求和处理响应。
快速入门
基本 GET 请求
import axios from "axios";
// Promise-based
axios
.get("/user?ID=12345")
.then((response) => console.log(response.data))
.catch((error) => console.error(error));
// Async/await
async function getUser() {
try {
const response = await axios.get("/user?ID=12345");
console.log(response.data);
} catch (error) {
console.error(error);
}
}
基本 POST 请求
axios
.post("/user", {
firstName: "John",
lastName: "Doe",
})
.then((response) => console.log(response.data))
.catch((error) => console.error(error));
常见模式
自定义实例
const api = axios.create({
baseURL: "https://api.example.com",
timeout: 1000,
headers: { "X-Custom-Header": "foobar" },
});
// Use the instance
api.get("/users").then((response) => console.log(response.data));
配置请求
axios({
method: "post",
url: "/user/12345",
data: {
firstName: "Fred",
lastName: "Flintstone",
},
headers: {
"Content-Type": "application/json",
Authorization: "Bearer token",
},
});
并发请求
function getUserAccount() {
return axios.get("/user/12345");
}
function getUserPermissions() {
return axios.get("/user/12345/permissions");
}
Promise.all([getUserAccount(), getUserPermissions()]).then(
([account, permissions]) => {
console.log("Account:", account.data);
console.log("Permissions:", permissions.data);
},
);
错误处理
基本错误处理
axios.get("/user/12345").catch(function (error) {
if (error.response) {
// Server responded with error status
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// Request was made but no response received
console.log(error.request);
} else {
// Error in request setup
console.log("Error", error.message);
}
});
自定义错误状态验证
axios.get("/user/12345", {
validateStatus: function (status) {
return status < 500; // Resolve only if status < 500
},
});
拦截器
请求拦截器
axios.interceptors.request.use(
(config) => {
// Add auth token to headers
const token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
响应拦截器
axios.interceptors.response.use(
(response) => {
// Transform response data
return response.data;
},
(error) => {
// Handle common errors
if (error.response?.status === 401) {
// Redirect to login
window.location.href = "/login";
}
return Promise.reject(error);
},
);
身份验证重试模式
const api = axios.create({ baseURL: "/api" });
api.interceptors.response.use(undefined, async (error) => {
if (error.response?.status === 401) {
await refreshToken();
return api(error.config); // Retry original request
}
throw error;
});
请求/响应配置
常见配置选项
const config = {
url: "/user",
method: "get",
baseURL: "https://api.example.com",
headers: { "X-Requested-With": "XMLHttpRequest" },
params: { ID: 12345 },
data: { firstName: "John" },
timeout: 5000,
responseType: "json",
withCredentials: false,
validateStatus: (status) => status >= 200 && status < 300,
};
FormData 上传
const formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("username", "john");
axios.post("/upload", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
下载进度
axios.get("/download/file", {
onDownloadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total,
);
console.log(`Download: ${percentCompleted}%`);
},
});
响应结构
Axios 响应包含:
{
data: {}, // Server response data
status: 200, // HTTP status code
statusText: 'OK', // HTTP status message
headers: {}, // Response headers
config: {}, // Request config
request: {} // Request object
}
最佳实践
- 使用实例来处理不同的 API 或配置
- 实现拦截器来处理身份验证、日志记录和错误
- 设置超时以防止请求挂起
- 在适当的层级处理错误
- 使用 TypeScript以获得更好的类型安全性
- 在组件卸载时取消请求
TypeScript 支持
import axios, { AxiosResponse } from "axios";
interface User {
id: number;
name: string;
email: string;
}
const response: AxiosResponse<User> = await axios.get<User>("/user/123");
const user: User = response.data;
评论
支持 Markdown