在跟着视频教程学习项目的时候使用了axios发送请求,但是只是跟着把代码粘贴上去,一些语法规则根本不太清楚,但是根据之前的博客学习了fetch了之后,一看axios的介绍就明白了。所以就直接展示axios的面试题吧
本文主要内容:
-
Axios 基本用法(GET/POST/PUT/DELETE、拦截器、超时、取消请求)
-
Axios vs Fetch 区别
-
为什么要二次封装 Axios,如何封装
-
在 Vue/React 项目中的实践
-
文件上传、请求重试、高级优化
📌 1. Axios 基础问题
Q1:Axios 是什么?它的特点是什么?
💡 回答要点
Axios 是一个 基于 Promise 的 HTTP 客户端,用于发送 HTTP 请求,支持浏览器和 Node.js。
✅ 特点:
- 自动解析 JSON (
response.data
直接返回 JSON) - 拦截器(Interceptors)(可以在请求/响应前后进行处理)
- 支持取消请求 (
CancelToken
) - 支持超时设置 (
timeout
参数) - 支持请求并发控制 (
axios.all()
) - 自动携带 Cookies (支持
withCredentials
)
Q2:Axios 和 Fetch 有什么区别?
💡 回答要点
对比项 | Axios | Fetch |
---|---|---|
自动解析 JSON | ✅ 是,response.data 直接是 JSON |
❌ 需要手动 response.json() |
请求/响应拦截器 | ✅ 支持 | ❌ 需要手动封装 |
超时设置 | ✅ timeout 选项 |
❌ 需要 AbortController 实现 |
取消请求 | ✅ CancelToken |
❌ 需要 AbortController |
错误处理 | ✅ catch 直接捕获 HTTP 错误 |
❌ 需检查 response.ok |
默认携带 Cookies | ✅ 是 | ❌ 需 credentials: 'include' |
👉 Axios 更易用,适用于企业级项目,Fetch 适合轻量级需求。
📌 2. Axios 高级用法
Q3:如何在 Axios 里发送 GET/POST/PUT/DELETE 请求?
💡 回答要点
js
// GET 请求
axios.get('/api/users').then(response => console.log(response.data));
// POST 请求
axios.post('/api/users', { name: "Alice" }).then(response => console.log(response.data));
// PUT 请求
axios.put('/api/users/1', { name: "Updated Alice" }).then(response => console.log(response.data));
// DELETE 请求
axios.delete('/api/users/1').then(response => console.log("Deleted"));
Q4:如何在 Axios 里设置请求头?
💡 回答要点
js
axios.get('/api/data', {
headers: { 'Authorization': 'Bearer token123' }
}).then(response => console.log(response.data));
Q5:如何使用 Axios 进行并发请求?
💡 回答要点
可以使用 axios.all()
进行多个请求并发处理:
js
axios.all([
axios.get('/api/user'),
axios.get('/api/orders')
]).then(axios.spread((userRes, ordersRes) => {
console.log(userRes.data, ordersRes.data);
}));
Q6:如何取消 Axios 请求?
💡 回答要点
使用 CancelToken
取消请求:
js
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/api/data', { cancelToken: source.token })
.then(response => console.log(response.data))
.catch(error => {
if (axios.isCancel(error)) {
console.log("Request canceled", error.message);
}
});
// 取消请求
source.cancel("Request aborted by user");
Q7:如何在 Axios 里设置超时?
💡 回答要点
js
axios.get('/api/data', { timeout: 5000 }) // 5 秒超时
.then(response => console.log(response.data))
.catch(error => console.error("Timeout or request error:", error));
📌 3. Axios 二次封装相关问题
Q8:为什么要对 Axios 进行二次封装?
💡 回答要点
- 减少代码重复 (比如每次请求都要加
headers
) - 统一错误处理 (拦截所有错误,防止每次
catch
) - 自动添加 Token(可以在拦截器里统一添加)
- 支持自定义请求实例 (可创建不同
baseURL
的 Axios 实例) - 提高可维护性(项目规模变大后更容易管理)
Q9:如何对 Axios 进行二次封装?
💡 回答要点
📌 1️⃣ 创建 axiosInstance
js
import axios from 'axios';
// 创建 Axios 实例
const axiosInstance = axios.create({
baseURL: "https://api.example.com",
timeout: 10000, // 超时 10s
headers: { "Content-Type": "application/json" }
});
// 添加请求拦截器(请求前统一处理)
axiosInstance.interceptors.request.use(config => {
const token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, error => Promise.reject(error));
// 添加响应拦截器(统一错误处理)
axiosInstance.interceptors.response.use(response => {
return response.data; // 直接返回 data,避免每次 `response.data`
}, error => {
console.error("API Error:", error.response?.status, error.message);
return Promise.reject(error);
});
export default axiosInstance;
📌 2️⃣ 使用封装的 axiosInstance
js
import axiosInstance from './axiosInstance';
axiosInstance.get("/users")
.then(data => console.log(data))
.catch(error => console.error("Request failed:", error));
Q10:如何在 Vue/React 项目中使用封装后的 Axios?
💡 回答要点
在 Vue/React 项目中,可以在 api
目录下创建一个 request.js
进行二次封装。
📌 Vue 里使用
js
import axiosInstance from './axiosInstance';
export function getUserList() {
return axiosInstance.get('/users');
}
// 在 Vue 组件中使用
getUserList().then(users => console.log(users));
📌 React 里使用
js
import React, { useEffect, useState } from "react";
import axiosInstance from "./axiosInstance";
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
axiosInstance.get("/users").then(setUsers);
}, []);
return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}
export default UserList;
📌 4. 高级问题
Q11:如何使用 Axios 处理文件上传?
💡 回答要点
js
const formData = new FormData();
formData.append("file", file);
axios.post('/upload', formData, {
headers: { "Content-Type": "multipart/form-data" }
}).then(response => console.log(response.data));
Q12:如何实现 Axios 的请求重试?
💡 回答要点
使用拦截器在请求失败时自动重试:
js
axiosInstance.interceptors.response.use(null, async error => {
if (error.config && !error.config.__isRetryRequest) {
error.config.__isRetryRequest = true;
return axiosInstance(error.config); // 重新发送请求
}
return Promise.reject(error);
});