下面我会用 “深入浅出” 的方式,向你讲明白:
Axios 是什么?怎么用?它和
fetch有什么区别?什么时候该用哪个?
全程通俗易懂,配有代码示例和对比,适合初学者和进阶者。
🌟 一、先打个比方:网络请求就像“点外卖”
你想吃 pizza 🍕,有两种方式:
方式1:直接打电话给餐厅(原始方式)📞
- 你得自己说清楚地址、电话、备注
- 餐厅可能说“听不清”,你得再打一次
- 没有进度条,不知道外卖到哪了
👉 这就像原生的 fetch
方式2:用美团/饿了么 App 📱
- 自动记住地址、电话
- 自动重试、显示进度、失败提醒
- 支持优惠券、评价、历史订单
👉 这就像 Axios
🔥 Axios = 更智能、更方便的“网络请求工具”
fetch= 浏览器自带的“基础请求功能”
🧱 二、Axios 是什么?
Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js。
它可以帮你:
- 发送
GET、POST、PUT、DELETE请求 - 自动转换 JSON 数据
- 拦截请求和响应(如加 token)
- 超时、重试、取消请求
- 在浏览器和 Node.js 中都能用
🚀 三、Axios 基本用法(代码示例)
1. 安装 Axios
npm install axios
2. 发送 GET 请求
import axios from 'axios'
// 获取用户列表
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.error('请求失败:', error)
})
3. 发送 POST 请求
axios.post('/api/login', {
username: 'admin',
password: '123456'
})
.then(res => {
console.log('登录成功', res.data)
})
4. 使用 async/await(推荐)
async function fetchUsers() {
try {
const response = await axios.get('/api/users')
console.log(response.data)
} catch (error) {
console.error('错误:', error.message)
}
}
🌐 四、fetch 是什么?
fetch 是 浏览器内置的 API,不需要安装,直接可用:
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err))
或用 async/await:
async function fetchUsers() {
const res = await fetch('/api/users')
const data = await res.json()
console.log(data)
}
🔍 五、Axios vs fetch 详细对比
| 特性 | Axios | fetch |
|---|---|---|
| ✅ 是否需要安装 | ❌ 需要 npm install axios | ✅ 浏览器原生支持 |
| ✅ 默认支持 JSON 转换 | ✅ 自动 response.data | ❌ 需手动 await res.json() |
| ✅ 错误处理 | ✅ HTTP 状态码非 2xx 会进 catch | ❌ 404/500 不会进 catch(除非网络错误) |
| ✅ 请求拦截 | ✅ 可统一加 token、日志 | ❌ 不支持(需封装) |
| ✅ 响应拦截 | ✅ 可统一处理错误、数据 | ❌ 不支持 |
| ✅ 取消请求 | ✅ 支持 CancelToken 或 AbortController | ✅ 支持 AbortController |
| ✅ 超时设置 | ✅ 可设置 timeout: 5000 | ❌ 原生不支持,需手动实现 |
| ✅ 上传进度 | ✅ 支持 onUploadProgress | ❌ 不支持 |
| ✅ 下载进度 | ✅ 支持 onDownloadProgress | ❌ 不支持 |
| ✅ Node.js 支持 | ✅ 支持 | ❌ 不支持(浏览器专属) |
| ✅ 默认携带 Cookie | ❌ 需配置 withCredentials: true | ❌ 需配置 credentials: 'include' |
📊 六、关键区别详解
1. 错误处理不同(最重要!)
// Axios:404、500 都会进入 catch
axios.get('/api/user/999')
.then(res => console.log(res.data))
.catch(err => console.error('出错了!')) // 404 会进这里 ✅
// fetch:404 不会进 catch!
fetch('/api/user/999')
.then(res => {
if (!res.ok) throw new Error('用户不存在')
return res.json()
})
.then(data => console.log(data))
.catch(err => console.error(err)) // 必须手动判断 res.ok ❌
⚠️ 这是
fetch最坑的一点:HTTP 错误不等于请求失败
2. 请求拦截 vs 手动封装
// Axios:全局加 token
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer ' + token
return config
})
// fetch:需要自己封装函数
function myFetch(url, options = {}) {
options.headers = {
...options.headers,
Authorization: 'Bearer ' + token
}
return fetch(url, options)
}
3. 上传进度条(文件上传场景)
// Axios:轻松监听进度
axios.post('/upload', formData, {
onUploadProgress: (progressEvent) => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
console.log(`上传进度: ${percent}%`)
}
})
// fetch:不支持进度事件 ❌
🎯 七、什么时候用哪个?
| 场景 | 推荐工具 | 理由 |
|---|---|---|
| ✅ 简单 GET 请求(如获取配置) | fetch | 无需安装,浏览器原生支持 |
| ✅ 小项目、静态页面 | fetch | 轻量,够用 |
| ✅ 需要上传/下载进度 | ✅ Axios | 唯一选择 |
| ✅ 企业级项目、复杂 API | ✅ Axios | 拦截器、错误统一处理 |
| ✅ Node.js 后端发请求 | ✅ Axios | fetch 不支持 Node.js(除非用实验特性) |
| ✅ 需要超时、重试机制 | ✅ Axios | 配置简单 |
| ✅ 需要统一加 token、日志 | ✅ Axios | 拦截器太香了 |
✅ 八、最佳实践建议
推荐方案:项目中优先使用 Axios
// 封装一个 api.js
import axios from 'axios'
const api = axios.create({
baseURL: 'https://your-api.com',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
})
// 请求拦截:加 token
api.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
// 响应拦截:统一错误处理
api.interceptors.response.use(
response => response.data,
error => {
if (error.response?.status === 401) {
// 跳转登录
window.location.href = '/login'
}
return Promise.reject(error)
}
)
export default api
使用:
const users = await api.get('/users')
const user = await api.post('/users', { name: '小明' })
🧩 九、fetch 也能变强(现代用法)
如果你坚持用 fetch,可以这样优化:
async function request(url, options = {}) {
const res = await fetch(url, {
...options,
credentials: 'include' // 携带 cookie
})
if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`)
return await res.json()
}
// 使用
try {
const data = await request('/api/users')
} catch (err) {
console.error(err.message) // 自动捕获 404/500
}
但依然不如 Axios 方便。
✅ 十、总结:一句话记住
| 工具 | 适合谁 | 类比 |
|---|---|---|
| Axios | 所有项目(尤其复杂项目) | 美团 App:功能全、体验好 |
| fetch | 简单项目、学习、轻量需求 | 直接打电话:基础可用,但麻烦 |
🎯 推荐:新手直接上手 Axios,少踩坑,效率高!