title: Angularjs routing on an express 4.0 backend API
body: <p>I have started an application where I use Express 4.0 server. I have set up the routes based heavily on a tutorial on scotch.io (<a href="http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4" rel="nofollow">http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4</a>), builiding a backend api to serve the front end SPA (angularjs). Here is an extract of the backend router:</p>
  
  <pre><code>router.route('/users')
     .get(function (req, res) {
         User.find(function(err, users) {
            if (err) {
               res.send(err);
            }
            else {
               res.json(users);
            }
         });
     })
  </code></pre>
  
  <p>Further down</p>
  
  <pre><code>// home page route (http://localhost:8080)
  router.get('/', function(req, res) {
     res.send('API ROOT');    
  });
  
  app.use('/api', router);
  </code></pre>
  
  <p>From the frontend i use just a get to get the users from the api:</p>
  
  <pre><code>$http.get('/api/users')
      .success(function(data) {
          $scope.users = data;
  });
  </code></pre>
  
  <p>and the angular routes are set up like this:</p>
  
  <pre><code>.when('/', {
      templateUrl: 'views/home.html',
      controller: 'MainController'
  })
  
  .when('/users', {
      templateUrl: 'views/user.html',
      controller: 'UserController'
  })
  </code></pre>
  
  <p>The index.html has a link to /users.</p>
  
  <p>When starting the server and goint into localhost:8080 it loads fine, and clicking the users loads the user.html view and lists the users.</p>
  
  <p>However, if i click refresh when browser is in localhost:8080/users</p>
  
  <p>I get:</p>
  
  <pre><code>Cannot get /users
  </code></pre>
  
  <p>Is it a controller issue?
  Or is it a problem with backend routing?</p>
  
  <p>Any feedback/suggestions would be very welcome!</p>
  
  <p>Searching some more, I see that there are several sollutions that might fix this:
  Either on the frontend (angular routes part) adding this to the end:</p>
  
  <pre><code>// &gt;&gt;&gt; redirect other routes to
  otherwise({
      redirectTo: '/'
  });
  </code></pre>
  
  <p>Or on the backend (after all your routes):</p>
  
  <pre><code>app.get('*', function(req, res){
      res.render('index.html');
  });
  </code></pre>
  
  <p>Which sollution is better (or is it reccomended to use both...?)</p>