class Ajax {
constructor(baseURL = '', timeout = 10000) {
this.baseURL = baseURL;
this.timeout = timeout;
this.interceptors = {
request: [],
response: []
};
}
request(config) {
// 处理请求拦截器
let chain = [this._dispatchRequest, undefined];
this.interceptors.request.forEach(interceptor => {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(interceptor => {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
_dispatchRequest(config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
let url = config.baseURL ? config.baseURL + config.url : config.url;
let data = config.data;
// 处理GET请求参数
if (config.method === 'GET' && data) {
const params = new URLSearchParams();
for (const key in data) {
params.append(key, data[key]);
}
url += '?' + params.toString();
data = null;
}
xhr.timeout = config.timeout || 10000;
xhr.open(config.method, url, true);
// 设置请求头
if (config.headers) {
for (const key in config.headers) {
xhr.setRequestHeader(key, config.headers[key]);
}
}
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
let response = xhr.responseText;
try {
response = JSON.parse(response);
} catch (e) {}
resolve({
data: response,
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders()
});
} else {
reject(new Error(`Request failed with status code ${xhr.status}`));
}
};
xhr.onerror = function() {
reject(new Error('Network Error'));
};
xhr.ontimeout = function() {
reject(new Error('Timeout'));
};
// 发送请求
if (data && typeof data === 'object') {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send(data);
}
});
}
get(url, config = {}) {
return this.request({
...config,
method: 'GET',
url
});
}
post(url, data, config = {}) {
return this.request({
...config,
method: 'POST',
url,
data
});
}
// 添加拦截器
useRequestInterceptor(fulfilled, rejected) {
this.interceptors.request.push({ fulfilled, rejected });
return this.interceptors.request.length - 1;
}
useResponseInterceptor(fulfilled, rejected) {
this.interceptors.response.push({ fulfilled, rejected });
return this.interceptors.response.length - 1;
}
// 移除拦截器
ejectRequestInterceptor(id) {
if (this.interceptors.request[id]) {
this.interceptors.request.splice(id, 1);
}
}
ejectResponseInterceptor(id) {
if (this.interceptors.response[id]) {
this.interceptors.response.splice(id, 1);
}
}
}
// 使用示例
const api = new Ajax('https://api.example.com');
// 添加请求拦截器
api.useRequestInterceptor(config => {
config.headers = config.headers || {};
config.headers['Authorization'] = 'Bearer token123';
return config;
});
// 添加响应拦截器
api.useResponseInterceptor(response => {
console.log('Response:', response);
return response.data;
}, error => {
console.error('Error:', error);
return Promise.reject(error);
});
// 发起请求
api.get('/user/123')
.then(data => console.log('User data:', data))
.catch(err => console.error('Error:', err));
api.post('/user', { name: 'John', age: 30 })
.then(data => console.log('Created user:', data))
.catch(err => console.error('Error:', err));
|