How to redirect the user back to the same page aft

2019-09-03 03:44发布

问题:

I am new to this whole node thing, and password is quite intriguing and seems to quite work for many of the authentications, so it looked cool.

Scenario: I wanted to say, /profile to proceed, only when user is logged in.

Here is the route I made,

var express = require('express');
var router = express.Router();

the rest is in the file called router/index.js

var passport = require('passport');
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;


router.post('/login', passport.authenticate('login', {
    successRedirect: '/home',
    failureRedirect: '/',
    failureFlash : true  
}));


router.get('/profile', ensureLoggedIn('/'), function(req, res){
    res.json({ user: req.user });
});

So, based on my understanding and willingness, when I did GET /profile, it had to go to login page, and then redirect to GET /profile. Unfortunately, since the login page is supposed to return home, it does so.

connect-ensure-login is what I expected to solve the problem, but it hasn't. How do I make it work as I needed?

回答1:

You should use successReturnToOrRedirect instead of successRedirect:

router.post('/login', passport.authenticate('login', {
  successReturnToOrRedirect : '/home',
  failureRedirect           : '/',
  failureFlash              : true  
}));