Last active
December 21, 2022 06:54
-
-
Save justsml/3dd0a799ada8da7cd15943ff254266de to your computer and use it in GitHub Desktop.
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
const checkForRedirect = (response) => { | |
// Check for temporary redirect (307), or permanent (308) | |
if (response.status === 307 || response.status === 308) { | |
const location = response.headers.get('location') | |
if (!location) { | |
return Promise.reject(new Error('Invalid HTTP Redirect! No Location header.')); | |
} | |
// You can change the behavior here to any custom logic: | |
// e.g. open a "confirm" modal, log the redirect url, etc. | |
return fetch(location) | |
// Bonus: this will handle recursive redirects ✨ | |
.then(checkForRedirect) | |
} | |
return response | |
}; | |
fetch('https://api.github.com/orgs/elite-libs') | |
// Next line will handle redirects | |
.then(checkForRedirect) | |
.then(response => response.json()) | |
.then(console.log) | |
.catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment