Created
April 17, 2023 15:59
-
-
Save tjinlag/689a34dbfd4899bc60fcf6f38bf95152 to your computer and use it in GitHub Desktop.
Simplified Implementation of window.fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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