How to use AngularJS routes with Express (Node.js) when a new page is requested?

with express 4, you probably want to catch all requests and redirect to angularjs index.html page. app.use(app.router); doesn't exist anymore and res.sendfile is deprecated, use res.sendFilewith an uppercase F.

app.post('/projects/', projectController.createProject);
app.get('/projects/:id', projectController.getProject);
app.get('*', function (req, res) {
    res.sendFile('/public/index.html');
});

put all your API routes before the route for every path app.get('*', function (req, res){...})


I would create a catch-all handler that runs after your regular routes that sends the necessary data.

app = express();
// your normal configuration like `app.use(express.bodyParser());` here
// ...
app.use(app.router);
app.use(function(req, res) {
  // Use res.sendfile, as it streams instead of reading the file into memory.
  res.sendfile(__dirname + '/public/index.html');
});

app.router is the middleware that runs all of your Express routes (like app.get and app.post); normally, Express puts this at the very end of the middleware chain automatically, but you can also add it to the chain explicitly, like we did here.

Then, if the URL isn't handled by app.router, the last middleware will send the Angular HTML view down to the client. This will happen for any URL that isn't handled by the other middleware, so your Angular app will have to handle invalid routes correctly.


I guess I should have clarified that I wasn't interested in using a template engine, but having Angular pull all of the HTML partials on it's own, Node is functioning completely as a static server here (but it won't be for the JSON API. Brian Ford shows how to do it using Jade here: http://briantford.com/blog/angular-express.html

My app is a single-page app, so I created an Express route for each possible URL pattern, and each of them does the same thing.

fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, content) {
    res.send(content);
});

I was assuming I would have to pass some request variables to Angular, but it looks like Angular takes care of it automatically.