Skip to main content

axios

· 3 min read

easy Axios

axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js 环境。简单的实现支持基本的 HTTP 请求方法(如 GET、POST),并能处理请求和响应,目的是为了了解其实现方法。

// 创建一个 Axios 类,用于封装 HTTP 请求的逻辑
class Axios {
// 构造函数,初始化默认配置
constructor() {
// 可以在这里添加更多的默认配置,如超时时间、请求头默认值等
this.defaults = {
baseURL: '',
headers: {
'Content-Type': 'application/json'
}
};
}

// 发送请求的核心方法
request(config) {
// 合并默认配置和用户传入的配置
const mergedConfig = { ...this.defaults, ...config };
const { url, method = 'GET', headers, data } = mergedConfig;

// 返回一个 Promise 对象,用于处理异步请求
return new Promise((resolve, reject) => {
// 创建一个 XMLHttpRequest 对象,用于发送 HTTP 请求
const xhr = new XMLHttpRequest();

// 打开一个请求,设置请求方法和请求 URL
xhr.open(method.toUpperCase(), url, true);

// 设置请求头
for (const header in headers) {
if (headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header]);
}
}

// 监听请求状态变化事件
xhr.onreadystatechange = function () {
// 当请求完成且状态码为 200 时,表示请求成功
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status >= 200 && xhr.status < 300) {
// 解析响应数据
let responseData;
try {
responseData = JSON.parse(xhr.responseText);
} catch (error) {
responseData = xhr.responseText;
}
// 构建响应对象
const response = {
data: responseData,
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
config: mergedConfig
};
// 解决 Promise,返回响应对象
resolve(response);
} else {
// 请求失败,拒绝 Promise 并返回错误信息
reject(new Error(`Request failed with status code ${xhr.status}`));
}
}
};

// 监听请求错误事件
xhr.onerror = function () {
// 请求发生网络错误,拒绝 Promise 并返回错误信息
reject(new Error('Network Error'));
};

// 发送请求,如果有数据则将数据作为请求体发送
xhr.send(data ? JSON.stringify(data) : null);
});
}

// 封装 GET 请求方法
get(url, config = {}) {
return this.request({ ...config, method: 'GET', url });
}

// 封装 POST 请求方法
post(url, data = {}, config = {}) {
return this.request({ ...config, method: 'POST', url, data });
}
}

// 创建一个 axios 实例,方便使用
const axios = new Axios();

// 示例使用
// 发送一个 GET 请求
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
console.log('GET Response:', response.data);
})
.catch(error => {
console.error('GET Error:', error.message);
});

// 发送一个 POST 请求
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => {
console.log('POST Response:', response.data);
})
.catch(error => {
console.error('POST Error:', error.message);
});