我有一个在 node、express 和 angular 中运行的应用程序。它有 2 个页面,一个用户个人资料页面和一个登录页面。我想这样做,如果用户未登录并且到达个人资料页面时,我会将您重定向到登录页面。问题是,不知何故,每次我尝试在节点中重定向用户时,我的 Angular 应用程序都没有收到 302 重定向调用(即使我没有发送任何 200 状态消息响应,响应也始终为 200)。任何帮助表示赞赏。这是我的代码:
节点js:
// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
//authentication
app.post('/login', auth.login);
app.get('/logout', auth.logout);
app.get('/user', auth.getCurrentUser);
...
function getCurrentUser (req, res) {
var user = req.user;
if (user && user.username) {
console.log("getCurrentUser succeeded on user "+ user);
res.json({
username: user.username
});
} else {
console.log("getCurrentUser failed")
res.redirect('/login');
}
}
...
//routes in node
exports.index = function(req, res){
console.log("rendering index page");
res.render('index');
};
exports.partials = function (req, res) {
var name = req.params.name;
res.render('partials/' + name);
};
角度:
when('/login', {
templateUrl: 'partials/login',
contorller: LoginCtrl
}).
...
when('/user', {
templateUrl: 'partials/user',
controller: UserCtrl
})
function UserCtrl($scope, $http, $location, $routeParams) {
$http.get('/user').
success(function(data, status, headers){
console.log("/user succeeded with status "+status);
//redirect the user
if (status == 302){
console.log("302 received, redirecting user to "+headers().location);
$location.path(headers.location);
}
console.log("CLIENT : "+data.username);
$scope.username = data.username;
});
};
到达 /user 页面时服务器上的输出:
getCurrentUser failed
GET /user 302 8ms - 40b
rendering index page
GET /login 304 80ms
rendering index page
客户端输出:
/user succeeded with status 200