2017-09-18 31 views
1

我希望能够给未经授权的用户个人后的页面重定向到登录,然后返回到后用户在登录后。采取用户返回到前一页(节点)登录后

我登录路线是这样的:

router.get('/login', function(req, res, next){ 
    if (req.user){ 
     res.redirect('/wall'); 
    } else { 
     res.render('login'); 
    } 
}); 

我的墙路由器是这样的:

router.get('/wall', function(req, res, next){ 
    res.render('wall'); 
}); 

文章网址将是这样的:

http://thisisnotarealdomain.com/wall#/post/ID 

我的堆栈是:和的NodeJS角的SPA

我该怎么办呢?

感谢,

+0

你使用会话来跟踪用户吗? –

+0

是的,快递'会话 –

+0

希望这有助于可能是一点点调整。 https://stackoverflow.com/questions/13335881/redirecting-to-previous-page-after-authentication-in-node-js-using-passport-js –

回答

1

首先,我想创建一个中间件的功能来处理的情况下,重定向用户没有登录,是这样的:

const checkLogin = (req, res, next) => { 

    // Checks if the user is logged in 
    if(!userIsLoggedIn) { 

    // If user is not logged in 

    // Get relative path of current url 
    const url = req.originalUrl; 

    // And redirect to login page, passing 
    // the url as a query string that Angular 
    // can access later 
    res.redirect(`/login/?redirect=${url}`); 

    } else { 

    // If user is logged in 
    // go on and render the page 
    next(); 

    } 
} 

router.get('/wall', checkLogin, function(req, res, next){ 
    res.render('wall'); 
}); 

这样,如果用户未登录,您将重定向到像 /login /?redirect =/wall/post/14这样的网址。

然后在您的Angular代码中,您将等待来自Node的登录承诺,并简单地重定向到我们拥有的查询字符串:重定向。事情是这样的:

// Assuming you're logging from a service 
angular 
    .service('LoginService', function($location, $window) { 

    // Generic login (could be $http, $resource, restangular) 
    LOGIN_PROMISE 
     .then(function(res) { 

     // If login was successful 
     if(res.success) { 

      // $location.search() allows you 
      // to access query strings 
      var redirectTo = $location.search().redirect; 

      // And then redirect to the page the 
      // user were before being redirected 
      // to the login page 
      $window.location.href = redirectTo; 

     } 

     }) 
    }) 

或者,你可以直接从你的后端代码进行重定向:

// On your Angular code 
$http({ 
    method: 'GET', 
    params: { 
    redirect: $location.search().redirect 
    } 
}); 

// On Node 
router.get('/api/login', (req, res, next) => { 

    if(passwordIsCorrect) { 
    // And do the redirect 
    res.redirect(req.body.redirect); 
    } 

}); 

这仅仅是一个很多的,你可以做到这一点(这是方法之一网络发展之美)。

希望这可以帮助你!

+0

谢谢你的队友。我会测试一下并回复给你。欢呼声 –

+0

“req.originalUrl;”没有任何东西超过#。请记住,我需要一个SPA应用程序的完整路径,如下所示:http://thisisnotarealdomain.com/wall#/post/ID –

+0

在网址上使用hashbang(#)是绝对重要的吗?如果不是的话,我会建议你在你的main html和$ locationProvider.html5Mode(true)一起使用;在你的路由配置文件中。这样你可以检索完整的路径。 –

相关问题