class HttpClient {
constructor(baseURL = '', defaultHeaders = {}) {
this.baseURL = baseURL;
this.defaultHeaders = defaultHeaders;
}
async request(method, url, options = {}) {
const { params, data, headers, ...restOptions } = options;
// Build URL with query parameters if they exist
let finalURL = this.baseURL + url;
if (params) {
const query = new URLSearchParams(params).toString();
finalURL += `?${query}`;
}
// Configure fetch options
const fetchOptions = {
method: method.toUpperCase(),
headers: {
'Content-Type': 'application/json',
...this.defaultHeaders,
...headers
},
...restOptions,
};
// Add body if necessary
if (data) {
fetchOptions.body = JSON.stringify(data);
}
try {
const response = await fetch(finalURL, fetchOptions);
// Check if the response is successful
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status} - ${response.statusText}`);
}
// Attempt to parse the response as JSON
const responseData = await response.json();
return responseData;
} catch (error) {
// Error handling
console.error('Fetch error:', error);
throw error;
}
}
get(url, options = {}) {
return this.request('GET', url, options);
}
post(url, data, options = {}) {
return this.request('POST', url, { ...options, data });
}
put(url, data, options = {}) {
return this.request('PUT', url, { ...options, data });
}
delete(url, options = {}) {
return this.request('DELETE', url, options);
}
}
const client = new HttpClient("https://[Log in to view URL]")
client.get("/api/v2/pokemon/ditto").then(response => console.log(response));
To embed this project on your website, copy the following code and paste it into your website's HTML: