How to redirect the user back to the same page after authentication?

不羁的心 提交于 2020-01-17 06:18:51

问题


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


来源:https://stackoverflow.com/questions/37634816/how-to-redirect-the-user-back-to-the-same-page-after-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!