😺😺😺 和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 底層原理詳解(按執行流程講)
- 運行環境判斷
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 環境
}
};
- 核心結構:axios 實例本質是一個函數 + 配置鏈式調用系統
Axios 是通過 axios.create() 創建一個帶默認配置的實例,其實本質是一個函數對象,并帶有攔截器、請求方法(get/post/put…)等屬性。
const axios = Axios.create();
axios.get(’/url’) // 就是在調用實例對象的方法
- 請求發送:根據環境走不同適配器
👉 瀏覽器中
使用的是 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();
- 請求流程組成(重點)
用戶調用 axios(config)
↓
合并默認配置 + 用戶配置
↓
執行請求攔截器鏈(request interceptors)
↓
調用適配器(xhr / http)發出請求
↓
獲取響應后執行響應攔截器鏈(response interceptors)
↓
返回 Promise 給調用者
- 攔截器機制(interceptors)
Axios 內部實現了一個 鏈式中間件系統,用來處理攔截器。
你添加的攔截器會被加入到一條“任務鏈”中執行,先執行 request 攔截器,再發請求,之后執行 response 攔截器:
interceptors.request.use(fn1);
interceptors.request.use(fn2); // 執行順序:fn1 → fn2
- 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,并通過“攔截器鏈”實現請求和響應邏輯的可擴展性。