I have an app running in node, express, and angular. It has 2 pages, a user profile page and a login page. I want to make it so that if the user is not signed on and when the profile page is reached, I will redirect you to the login page. The problem is, somehow every time I try to redirect the user in node my Angular app doesn't receive the 302 redirect call (the response is always 200 even when I'm not sending any 200 status message responses). Any help is appreciated. Here is my code:
Node 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);
};
angular:
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;
});
};
Output on server when /user page is reached:
getCurrentUser failed
GET /user 302 8ms - 40b
rendering index page
GET /login 304 80ms
rendering index page
Output on client:
/user succeeded with status 200
The 302 sent back by Express is handled by your browser, before Angular even gets its hands on it (so you can't create an interceptor for it).
A solution would be to always return a JSON object, and set some property on it that you can check for in Angular.