Making redirects after an axios post request with express Making redirects after an axios post request with express express express

Making redirects after an axios post request with express


I figured this out after. Apparently, you cannot do a redirect from the server when you make an Axios post request. At least not the way that I was doing it (with the default Axios config.) You need to do the page change on the client side. Here's how I did it.

This really stumped me because I was receiving data from my redirect route using the other method but the page wasn't loading.

Also, for some reason using Next.js, the passport.js "successRedirect" and "failureRedirect" JSON doesn't seem to work. That's why I've written the routing the way I have and did not include those in the passport.authenticate() function. I hope this helps somebody!

My Axios submit function:

onSubmit = (e) => {    e.preventDefault()    const {username, password} = this.state;    axios.post('/login', {username: username, password: password})        .then(function (response) {            if (response.data.redirect == '/') {                window.location = "/index"            } else if (response.data.redirect == '/login'){                window.location = "/login"            }        })        .catch(function(error) {            window.location = "/login"        })}

The post request in my Express server

server.post('/login', passport.authenticate('local'), (req, res, next) => {    if (req.user) {        var redir = { redirect: "/" };        return res.json(redir);  } else {        var redir = { redirect: '/login'};        return res.json(redir);  }})


Although it won't be a server-side redirect, this can be accomplished cleanly on the client-side with Axios' "interceptor" which can intercept requests or responses before they get passed to then/catch:

// Add a request interceptoraxios.interceptors.request.use(function (config) {    // Do something before request is sent    return config;  }, function (error) {    // Do something with request error    return Promise.reject(error);  });// Add a response interceptoraxios.interceptors.response.use(function (response) {    // Do something with response data    return response;  }, function (error) {    // Do something with response error    return Promise.reject(error);  });

https://github.com/axios/axios#interceptors