4

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 redirection url is received in the fetch() api response body. After this what should I do to redirect user to this URL from fetch function.

fetch("/events/registration", {
          method: "POST",
          redirect:"follow",
          headers: {
            "Accept": "application/json , text/plain ,*/*",
            "Content-type": "application/json"
          },
          body: JSON.stringify({
            name,
            email,
          })
        })
.then((res)=>res.json())
.then((data)=>{console.log(data);if(data.err)alert(data.err);Response.redirect()});

In response that i receive in fetch api I am getting redirect:true , url: "LinkOfRedirection/redirect", now what should i do to redirect user from here to the LinkOfRedirection/redirect.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ayush Agrawal
  • 69
  • 1
  • 1
  • 5

2 Answers2

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);
Vishnu R
  • 108
  • 1
  • 10
  • 1
    is there a way to redirect the user from the fetch api itself – Ayush Agrawal Jan 29 '19 at 05:30
  • fetch api doesnot have a redirect default method . Please refer to this https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – Vishnu R Jan 29 '19 at 05:43
  • 4
    @VishnuR When I set window.loaction=res.url how can I pass the data? I am redirecting to dashboard and all the data that need to be plotted in dashboard should be fetched from database first otherwise dashboard will show nothing. – ttfreeman May 10 '19 at 18:27
0

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)
    }

})