login后将用户带回上一页(节点)

我希望能够将未经身份validation的用户从单个post的页面redirect到login,然后在用户login后重新回到post。

我的login路线是这样的:

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

post的URL将会是这样的:

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

我的堆栈是:SPA的NodeJS和Angular

我怎么做?

谢谢,

Solutions Collecting From Web of "login后将用户带回上一页(节点)"

首先,我会创build一个中间件函数来处理用户未login的redirect,如下所示:

 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到像/ login /?redirect = / wall / post / 14这样的url。

然后在您的Angular代码中,您将等待来自Node的login许诺,并简单地redirect到我们拥有的查询string: redirect 。 像这样的东西:

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

或者你可以直接从你的后端代码做一个redirect:

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

这只是你可以做到这一点的很多方法之一(这就是网站开发的美妙之处)。

希望这可以帮助你!