const HttpClient = { baseURL: 'https://api.example.com', headers: {},
setBaseURL(url) { this.baseURL = url; },
setHeaders(headers) { this.headers = { ...this.headers, ...headers }; },
async request(method, endpoint, data = null) { const url = `${this.baseURL}${endpoint}`; const options = { method, headers: this.headers };
if (data) { options.body = JSON.stringify(data); }
const response = await fetch(url, options); return response.json(); },
get(endpoint) { return this.request('GET', endpoint); },
post(endpoint, data) { return this.request('POST', endpoint, data); },
put(endpoint, data) { return this.request('PUT', endpoint, data); },
delete(endpoint) { return this.request('DELETE', endpoint); } };
HttpClient.setBaseURL('https://api.example.com/v1'); HttpClient.setHeaders({ 'Content-Type': 'application/json' });
HttpClient.get('/users').then(data => console.log(data)); HttpClient.post('/users', { name: '张三', email: 'zhang@example.com' }) .then(data => console.log(data));
|