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

😺😺😺 和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,并通过"拦截器链"实现请求和响应逻辑的可扩展性。
相关推荐
FRing035 小时前
vue2干货总结7(自定义指令、插槽、单页应用程序、路由的使用(VueRouter))
开发语言·前端·vue.js·vue2
ruanno_top9 小时前
点全选,已选的被清空了:Transfer 三态复选框的三个 bug
vue.js
时间的情敌10 小时前
Cesium 加载 3D Tiles 倾斜摄影、压平、样式设置(Vue3 实战)
vue.js·3d·cesium
usdoc文档预览1 天前
USDOC系列之PPT文件在线编辑-VUE前端实现在线浏览器在线编辑PPT文档
前端·vue.js·编辑器·office365·ppt在线编辑·office文件在线编辑·文件在线编辑
Java小卷1 天前
面向 schema 编程,轻松搞定 Element 虚拟化表格复杂应用场景
vue.js·低代码·element
仨孩子的爹1 天前
Lodop、hiprint 与 vue-print-designer:打印控件选型对比
vue.js
ruanno_top1 天前
四个 canvas 组件,在 2 倍屏上一直是糊的
vue.js
ruanno_top1 天前
一个脏数据能让整条折线消失:图表组件的四种数据契约
vue.js
FlyWIHTSKY2 天前
vue2和vue3有什么区别,用法上有哪些区别
前端·javascript·vue.js
ruanno_top2 天前
能点,但 Tab 不到:两个组件把「可操作」做了一半
vue.js