首先,我想创建一个中间件的功能来处理的情况下,重定向用户没有登录,是这样的:
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);
}
});
这仅仅是一个很多的,你可以做到这一点(这是方法之一网络发展之美)。
希望这可以帮助你!
你使用会话来跟踪用户吗? –
是的,快递'会话 –
希望这有助于可能是一点点调整。 https://stackoverflow.com/questions/13335881/redirecting-to-previous-page-after-authentication-in-node-js-using-passport-js –