I have a button with functionality that requires the user to authenticate. If the user is not authenticated the link should redirect to the login page. When I click the button, from the devtools network tab I can see the fetch api first calls the original url which returns a status code 302 and then another call which returns the login page. So Instead of calling the login page after a 302 status code, I want to redirect the page there.
I have tried to use the location header but the result is always null and also for some reason the if(res.status == 302) block never executes
Here is the code
fetch(`https://example.com`)
.then(res => {
if(res.status == 302) {
window.location.href = res.headers.get('location');
}
else if (res.ok) return res.text();
else console.log(`Error: ${res.status}`);
})
.then(data => {
// Do something
})
.catch(e => {
console.error(e);
});
});