我希望能够将未经身份验证的用户从单个帖子的页面重定向到登录,然后在用户登录后返回到帖子。
我的登录路线是这样的:
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和Angular for SPA
我该怎么做?
谢谢,
答案 0 :(得分: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');
});
这样,如果用户未登录,您将被重定向到类似的URL 的 /登录/?重定向= /壁/后/ 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);
}
});
这只是您实现这一目标的众多方式之一(这是网络开发之美)。
希望这可以帮到你!