Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created April 17, 2023 15:59
Show Gist options
  • Save tjinlag/689a34dbfd4899bc60fcf6f38bf95152 to your computer and use it in GitHub Desktop.
Save tjinlag/689a34dbfd4899bc60fcf6f38bf95152 to your computer and use it in GitHub Desktop.
Simplified Implementation of window.fetch
function fetch(url, options) {
// create a new Promise object
return new Promise((resolve, reject) => {
// create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// handle the response from the server
xhr.onload = () => {
const response = new Response(xhr.responseText, {
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders()
});
resolve(response);
};
// handle any errors that occur while fetching
xhr.onerror = () => {
reject(new TypeError('Network request failed'));
};
// open the connection to the server
xhr.open(options.method || 'GET', url);
// set any headers that were provided
for (const header in options.headers) {
xhr.setRequestHeader(header, options.headers[header]);
}
// send the request to the server
xhr.send(options.body);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment