class MyAxios {
constructor(defaultConfig) {
this.defaultConfig = defaultConfig || {};
}
request(config) {
return new Promise((resolve, reject) => {
const finalConfig = { ...this.defaultConfig, ...config };
let xhr = new XMLHttpRequest();
finalConfig.url = finalConfig.baseURL + finalConfig.url;
if (finalConfig.params) {
const params = new URLSearchParams(finalConfig.params).toString();
finalConfig.url += `?${params}`;
}
xhr.open(finalConfig.method || 'GET', finalConfig.url);
if (finalConfig.method === 'POST' && !xhr.getAllResponseHeaders().includes('Content-Type')) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(xhr.responseText);
}
}
};
if (finalConfig.method === 'POST') {
xhr.send(new URLSearchParams(finalConfig.data).toString());
} else {
xhr.send();
}
});
}
}
const axiosInstance = new MyAxios({
baseURL: 'https://api.example.com'
});
axiosInstance.request({
url: '/endpoint',
method: 'POST',
data: { key: 'value' },
params: { query: 'example' },
}).then(response => {
console.log(response);
}).catch(error => {
console.error(error);
});
实现axios
最新推荐文章于 2024-11-10 15:10:09 发布