Axios 相关的面试题

在跟着视频教程学习项目的时候使用了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。

特点

  • 自动解析 JSONresponse.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 进行二次封装?

💡 回答要点
  1. 减少代码重复 (比如每次请求都要加 headers
  2. 统一错误处理 (拦截所有错误,防止每次 catch
  3. 自动添加 Token(可以在拦截器里统一添加)
  4. 支持自定义请求实例 (可创建不同 baseURL 的 Axios 实例)
  5. 提高可维护性(项目规模变大后更容易管理)

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);
});

相关推荐
夏幻灵5 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_5 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝5 小时前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions5 小时前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发5 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
程序员猫哥_5 小时前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html
龙飞055 小时前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl
我爱加班、、5 小时前
Websocket能携带token过去后端吗
前端·后端·websocket
AAA阿giao5 小时前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
杨超越luckly5 小时前
HTML应用指南:利用GET请求获取中国500强企业名单,揭秘企业增长、分化与转型的新常态
前端·数据库·html·可视化·中国500强