9.axios底层原理,和promise的对比(2)

发布于:2025-06-06 ⋅ 阅读:(21) ⋅ 点赞:(0)

😺😺😺 和promise的对比
完全可以直接使用 Promise 来发 HTTP 请求,比如用原生 fetch + Promise 就可以实现网络请求功能👇

✅ 用 Promise + fetch 的写法(原生)

fetch(‘https://api.example.com/data’)
.then(response => {
if (!response.ok) {
throw new Error(‘网络请求失败’);
}
return response.json();
})
.then(data => {
console.log(‘获取到的数据:’, data);
})
.catch(error => {
console.error(‘出错了:’, error);
});

或者配合 async/await:

async function getData() {
try {
const res = await fetch(‘https://api.example.com/data’);
const data = await res.json();
console.log(data);
} catch (err) {
console.error(‘请求失败:’, err);
}
}

❓那为什么还要用 Axios?

你可以把 Axios 理解为在 Promise 的基础上,做了很多贴心的“增强封装”,避免你自己重复造轮子,比如

✅ 小结一句话
完全可以用Promise 来发 HTTP 请求,比如用原生 fetch + Promise 就可以实现网络请求功能👇

✅ 用 Promise + fetch 的写法(原生)

fetch(‘https://api.example.com/data’)
.then(response => {
if (!response.ok) {
throw new Error(‘网络请求失败’);
}
return response.json();
})
.then(data => {
console.log(‘获取到的数据:’, data);
})
.catch(error => {
console.error(‘出错了:’, error);
});

或者配合 async/await:

async function getData() {
try {
const res = await fetch(‘https://api.example.com/data’);
const data = await res.json();
console.log(data);
} catch (err) {
console.error(‘请求失败:’, err);
}
}

❓那为什么还要用 Axios?

你可以把 Axios 理解为在 Promise 的基础上,做了很多贴心的“增强封装”,避免你自己重复造轮子,比如

在这里插入图片描述

✅ 小结一句话

Promise 是底层机制;fetch 是浏览器原生 API;Axios 是基于 Promise 的高级封装,帮你做了更多重复性的工作。

所以结论是:
• ✅ 想极简 + 自己控制逻辑:可以直接用 fetch + Promise
• 🚀 想方便 + 拦截器 + 项目统一封装:推荐用 Axios

😺😺😺 aixos的底层原理
lAxios 的底层原理,可以把它理解为一层「统一的网络请求封装」,根据运行环境自动调用不同的底层实现。

✅ 一句话概括:

Axios 是一个对浏览器的 XMLHttpRequest 和 Node.js 的 http 模块的封装,并结合了 Promise、拦截器、中间件机制等高级功能的请求库。

🧩 Axios 底层原理详解(按执行流程讲)

  1. 运行环境判断

Axios 的代码是通用的,在构建时自动根据环境(浏览器 vs Node)使用不同适配器:

// 源码片段
var getDefaultAdapter = function getDefaultAdapter() {
if (typeof XMLHttpRequest !== ‘undefined’) {
return require(’./adapters/xhr’); // 浏览器环境
} else if (typeof process !== ‘undefined’) {
return require(’./adapters/http’); // Node.js 环境
}
};

  1. 核心结构:axios 实例本质是一个函数 + 配置链式调用系统

Axios 是通过 axios.create() 创建一个带默认配置的实例,其实本质是一个函数对象,并带有拦截器、请求方法(get/post/put…)等属性。

const axios = Axios.create();
axios.get(’/url’) // 就是在调用实例对象的方法

  1. 请求发送:根据环境走不同适配器

👉 浏览器中

使用的是 XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send(data);

👉 Node.js 中

使用的是 http 或 https 模块

const http = require(‘http’);
const req = http.request(options, res => {
// 处理响应
});
req.write(data);
req.end();

  1. 请求流程组成(重点)

用户调用 axios(config)

合并默认配置 + 用户配置

执行请求拦截器链(request interceptors)

调用适配器(xhr / http)发出请求

获取响应后执行响应拦截器链(response interceptors)

返回 Promise 给调用者

  1. 拦截器机制(interceptors)

Axios 内部实现了一个 链式中间件系统,用来处理拦截器。

你添加的拦截器会被加入到一条“任务链”中执行,先执行 request 拦截器,再发请求,之后执行 response 拦截器:

interceptors.request.use(fn1);
interceptors.request.use(fn2); // 执行顺序:fn1 → fn2

  1. Promise 化封装

Axios 所有操作都是 Promise 化的,便于使用 async/await,也方便链式 .then() 调用。

return new Promise((resolve, reject) => {
xhr.onload = () => resolve(response);
xhr.onerror = () => reject(error);
});

🧠 总结一句话:

Axios 底层是通过环境适配调用 XHR 或 Node 的 HTTP 模块,外部暴露统一的 Promise 风格 API,并通过“拦截器链”实现请求和响应逻辑的可扩展性。

网站公告

今日签到

点亮在社区的每一天
去签到