Home  >  Q&A  >  body text

Redirect after axios post request in Express

I am unable to redirect after accepting a post request from Axios. I do know that the request is being sent and it's at least getting some response from the '/' route because my console logs "index", "user-authentication" which is what should happen when someone makes a get request to '/' '. The problem is that the page won't load. I even see index.js loaded in Google Chrome's network tab, but no matter what I try, the page won't change! Is there any reason for this?

The other redirects I made seem to work. For example, if the user is not logged in, the index page will be rerouted to /login. This seems to be just an issue with the post request, I've tested it with and without passport auth (obviously changed to you need to be logged in to redirect) and the results are the same. So I don't think the passport is causing the problem.

You can refer to the package.json below to see what I am using

axios code:

axios.post('/login', {username: username, password: password})
        /*.then(response => res.redirect('/'))*/
        .then(function (response) {
            console.log(response);
        })
        .catch(function(error) {
            console.log(error);
        })

Expression aspect: I have console logs to remind myself during testing

server.get('/', (req,res) =>{
    console.log("Index");
  if (req.user){
       console.log("user verified");
        res.redirect('/');
        app.render(req,res, '/',req.query);
  } else {
      console.log("user not logged in");
      res.redirect('/login');
  }
})

server.post('/login', passport.authenticate('local'), (req, res, next) => {
    if (req.user) {
        console.log("Logging in");
        res.redirect('/');
  } else {
        console.log("Passwrod Incorrect");
        return res.redirect('/login');
  }
})

package.json

{
  "name": "layout-component",
  "version": "1.0.0",
  "scripts": {
    "dev": "node ./server.js",
    "build": "next build",
    "start": "NODE_ENV=production node ./server.js"
  },
  "dependencies": {
    "@zeit/next-css": "^0.1.5",
    "axios": "^0.18.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.18.2",
    "connect-flash": "^0.1.1",
    "connect-mongo": "^2.0.1",
    "cookie-parser": "^1.4.3",
    "express": "^4.16.3",
    "express-session": "^1.15.6",
    "express-validator": "^5.1.0",
    "file-loader": "^1.1.11",
    "hoist-non-react-statics": "^2.5.0",
    "jsonwebtoken": "^8.2.0",
    "mongodb": "^3.0.5",
    "mongoose": "^5.0.12",
    "next": "^5.1.0",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "prop-types": "^15.6.1",
    "react": "^16.3.0",
    "react-dom": "^16.3.0",
    "semantic-ui-css": "^2.3.1",
    "semantic-ui-react": "^0.79.0",
    "url-loader": "^1.0.1"
  },
  "license": "ISC"
}


P粉715304239P粉715304239368 days ago691

reply all(1)I'll reply

  • P粉674876385

    P粉6748763852023-10-18 13:12:41

    I figured this out later. Apparently when you make an Axios post request you can't redirect from the server. At least not the way I do it (using the default Axios configuration). You need to make page changes on the client side. Here's what I did.

    This is really confusing to me because I'm using other methods to receive data from the redirect route but the page is not loading.

    Also, using Next.js for some reason, the passport.js "successRedirect" and "failureRedirect" JSONs don't seem to work. That's why I wrote the route the way I did and didn't include it in the Passport.authenticate() function. I hope this helps someone!

    My axios submission 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"
            })
    }

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

    reply
    0
  • Cancelreply