菜鸟-创作你的创作

一文详解fetch,ajax,axios的区别以及使用

下面给你一份 《一文看懂 fetch、AJAX、Axios 的区别与使用(2025 最全详解版)》,可直接当成博客文章或学习笔记,结构清晰、例子全。


🧩 一文详解:fetch、ajax、axios 的区别与使用(2025 最新总结)

Web 前端中最重要的能力之一就是执行 HTTP 请求。目前主流方式有:

它们各自出现的时代、定位和使用方式都不同。

本文从 概念 → 区别 → 优缺点 → 代码示例 → 选型建议 一次讲清。


🔥 1. 基础概念

1.1 AJAX(XMLHttpRequest)

AJAX = Asynchronous JavaScript and XML
本质是使用 XMLHttpRequest(XHR) 发送异步请求。

出现于 2005 年,是以前唯一的异步请求方式。


1.2 fetch(原生 API)

Fetch API 是浏览器内置的现代异步请求方式
支持 Promise、支持 async/await。

出现于 2015 年,现在已成为 Web 标准。


1.3 Axios(第三方封装库)

基于 XHR 封装的网络请求库
提供更好的 API、更强的功能支持。


🔍 2. fetch、AJAX、axios 的核心区别

特性AJAX(XHR)fetchAxios
是否原生✔ 原生✔ 原生❌ 第三方
API 使用体验❌ 复杂✔ Promise✔ 更优雅
是否支持 Promise❌ 不支持
需要手动处理 JSON
处理错误方式❌ 很繁琐❌ 只对网络错误 reject✔ 网络 + 状态码统一处理
浏览器支持✔ 兼容性最佳✔ IE 不支持✔ 需要 polyfill
拦截器❌ 没有❌ 没有✔ 强大
请求取消❌ 需要手写✔ AbortController✔ 内置 cancelToken
超时设置❌ 麻烦❌ 需自行封装✔ 内置
文件上传✔ 最完善
默认携带 cookie
体积原生原生~14KB

🧠 3. 用一句话总结三者


😊 4. 基础用法对比


4.1 AJAX(XMLHttpRequest)写法示例

(经典但繁琐)

const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  }
};
xhr.send();

问题:


4.2 fetch 写法示例

fetch('/api/data')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

使用 async/await 更优雅:

async function getData() {
  try {
    const res = await fetch('/api/data');
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

但 fetch 需要注意:
🚨 状态码 400/500 不会 reject,需要手动处理

if (!res.ok) throw new Error("HTTP Error " + res.status);


4.3 axios 写法(最干净)

axios.get('/api/data')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

或 async/await:

async function getData() {
  try {
    const { data } = await axios.get('/api/data');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}


🎯 5. 实战能力对比

✔ 5.1 错误处理

fetch

只有 网络错误 才会进入 catch

fetch('/api')
  .then(res => {
    if (!res.ok) throw new Error("status:" + res.status);
    return res.json();
  })
  .catch(console.error);

axios

状态码 + 网络错误都能 catch

axios.get('/api').catch(err => console.error(err));


✔ 5.2 超时

fetch(需要封装)

const controller = new AbortController();
setTimeout(() => controller.abort(), 3000);

fetch('/api', { signal: controller.signal });

axios(自带)

axios.get('/api', { timeout: 3000 });


✔ 5.3 携带 cookie

fetch

fetch('/api', { credentials: 'include' });

axios

默认就会携带


✔ 5.4 拦截器(fetch 没有)

axios

axios.interceptors.request.use(config => {
  config.headers.Authorization = 'token123';
  return config;
});


🧩 6. 使用场景总结

场景推荐
简单 GET/POSTfetch
企业级项目axios
需要拦截器(token)axios
上传文件axios 或 XHR
高定制需求、无需第三方fetch
IE 兼容项目XHR

🎉 7. 结论(最简明)

2025 年前端项目中:

使用率排序:Axios > fetch > XHR

退出移动版