剖析 Axios 源码(三):适配器
2024-01-04 06:37:53
Axios 是一个基于 Promise 的 HTTP 客户端,它允许你在浏览器和 Node.js 中轻松地发送 HTTP 请求。Axios 的一个重要特性是它支持多种适配器,使它能够与不同的网络请求库集成。在 Axios 中,适配器是一个负责将 Axios 请求转换为特定网络请求库请求的函数。它允许 Axios 与不同的网络请求库集成,例如 Fetch、Node.js 内置的 HTTP 模块和 XML Http Request (XHR)。
适配器概述
适配器的作用是将 Axios 的请求逻辑转换为特定网络请求库的请求逻辑。这使得 Axios 能够在不同的环境中使用,例如浏览器和 Node.js。
Axios 内置的适配器
Axios 内置了三个适配器:
- Fetch 适配器:用于在浏览器中使用 Fetch API 发送请求。
- Node.js 适配器:用于在 Node.js 中使用 Node.js 内置的 HTTP 模块发送请求。
- XML Http Request (XHR) 适配器:用于在浏览器中使用 XHR 发送请求。
Fetch 适配器解析
Fetch 适配器位于 /adapters/fetch.js
文件中。它是一个简单的函数,接受一个 Axios 请求对象作为参数,并返回一个 Promise。这个 Promise 将在请求完成后解析,并包含响应数据。
export default function fetchAdapter(config) {
return new Promise((resolve, reject) => {
fetch(config.url, config).then(response => {
if (response.ok) {
resolve(response.json());
} else {
reject(new Error(`请求失败:${response.status}`));
}
}).catch(error => {
reject(error);
});
});
}
使用示例
假设你需要发送一个 GET 请求到 https://api.example.com/data
,你可以这样使用 Fetch 适配器:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Node.js 适配器解析
Node.js 适配器位于 /adapters/http.js
文件中。它也是一个简单的函数,接受一个 Axios 请求对象作为参数,并返回一个 Promise。这个 Promise 将在请求完成后解析,并包含响应数据。
export default function httpAdapter(config) {
return new Promise((resolve, reject) => {
const http = require('http');
const https = require('https');
const protocol = config.url.startsWith('https') ? https : http;
const request = protocol.request(config.url, config, (response) => {
let body = '';
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
resolve({
data: body,
status: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
});
});
});
request.on('error', (error) => {
reject(error);
});
request.end();
});
}
使用示例
假设你需要发送一个 GET 请求到 https://api.example.com/data
,你可以这样使用 Node.js 适配器:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
XHR 适配器解析
XHR 适配器位于 /adapters/xhr.js
文件中。它也是一个简单的函数,接受一个 Axios 请求对象作为参数,并返回一个 Promise。这个 Promise 将在请求完成后解析,并包含响应数据。
export default function xhrAdapter(config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(config.method, config.url, true);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
headers: getHeaders(xhr),
});
} else {
reject(new Error(`请求失败:${xhr.status}`));
}
};
xhr.onerror = () => {
reject(new Error('网络错误'));
};
xhr.send(config.data);
});
}
使用示例
假设你需要发送一个 GET 请求到 https://api.example.com/data
,你可以这样使用 XHR 适配器:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
总结
在本文中,我们解析了 Axios 源码中的适配器部分。我们了解了适配器的作用,以及 Axios 内置的三个适配器:Fetch 适配器、Node.js 适配器和 XHR 适配器。通过这些适配器,Axios 可以与不同的网络请求库集成,从而支持在浏览器和 Node.js 中轻松地发送 HTTP 请求。
如果你想深入了解 Axios 的源码,可以访问 Axios GitHub 仓库。在这个仓库中,你可以找到所有的源码文件和详细的文档。希望这篇文章对你有所帮助!