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