Express res.render not working with Angular routing

I have a web app based on node.js, express, angular (with routes) and mongo. Authentication is handled through Passport.js.

My angular views interact with the server through http requests. Say I send a request of type:

$http.get('/api/getMyData').success(function(data) {})...

on the server I have:

 app.get('/api/getMyData',function(req, res) {
    if(!req.user){
    // if the session expired
    res.render('login.ejs',{message:'Session expired. Please login again.'});

With this code I would like the user to be redirected to the login page if the session has expired.

Now, this is not working, and I get not redirected to login. Even if I have console.log(req.user) producing undefined and req.user==undefined giving true, the res.render within the if does not work. And if I try with res.redirect('login'); I get a 404 error saying that /api/login does not exist.

I am really getting lost with this, any help would be highly appreciated.

Your $http.get() is getting the contents back from res.render(). You can see this by adding console.log(data); in $http.get().success() You'll need to add some logic to your client to redirect if there is an error from the api.

Something like:

server.js

app.get('/api/getMyData', function(req, res) {
  if(!req.user) {
    res.status(401);
    return res.json({
      status: 'error',
      message: 'Unauthorized'
    });
  }
  return res.json({
    status: 'success',
    // Stuff
  });
}

Angular

$http.get('/api/getMyData').success(function(data) {
  // Do something
}).error(function(data, status) {
  // Handle the error
});

Note: This is untested but it will give you a general idea. There may be a more elegant solution.

I implemented something similar to what @Jordonias suggested. I get the user from the server (null if the session expired), and if the user is null I use $window.location.href="/login"; to logout the user. Thanks to @Jordonias. Better alternatives are welcome.