Skip to content Skip to sidebar Skip to footer

How To Redirect User To A Page After Receiving The Response From A Fetch Post Request?

I am writing code for a web application that send a POST request to node.js server using fetch() api of javascript. On successful request server responds with a redirection, this

Solution 1:

// Sets the new location of the current window.window.location = res.url;

// Sets the new href (URL) for the current window.window.location.href = res.url;

// Assigns a new URL to the current window.window.location.assign(res.url);

// Replaces the location of the current window with the new one.window.location.replace(res.url);

// Sets the location of the current window itself.
self.location = res.url;

// Sets the location of the topmost window of the current window.
top.location = res.url;

Or you can use

res.redirect(301, res.url);

Solution 2:

A simple solution to this would be something like this:

fetch('/api/login/' , { method : 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken' : csrf, },

    body : JSON.stringify(data)
}).then(result => result.json())
.then(response => {
    
    if(response.status == 200){
        window.location.href = '/'
    }
    else{
        alert(response.message)
    }

})

Post a Comment for "How To Redirect User To A Page After Receiving The Response From A Fetch Post Request?"