How to read redirect url from 3xx fetch response?

by filiberto , in category: Third Party Scripts , 2 months ago

How to read redirect url from 3xx fetch response?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 2 months ago

@filiberto 

When making a fetch request and receiving a 3xx status code as a response, the fetch API automatically follows the redirection and returns the final response. If you need to read the redirect URL, you can access it from the final response by checking the url property of the Response object. Here's an example of how you can do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fetch('https://example.com')
  .then(response => {
    if (response.redirected) {
      console.log('Redirected to:', response.url);
    }
    // handle the response as needed
  })
  .catch(error => {
    console.error('Error:', error);
  });


In this example, we check if the response has been redirected by checking the redirected property of the Response object. If it has been redirected, we log the final URL to the console using the url property.


You can then use this URL for further processing or to extract any necessary information from it.