AngularJS routing in ExpressJS AngularJS routing in ExpressJS express express

AngularJS routing in ExpressJS


In order to use AngularJS html5mode along with Express, you must serve "index.html" for all requests to leave all routing up to AngularJS. I had this same problem a while back.

So first, you declare all API endpoint routes, any static file directories (CSS, JS, partials, etc), and then serve index.html for all remaining requests. For example:

    // serve all asset files from necessary directories    app.use("/js", express.static(__dirname + "/app/js"));    app.use("/img", express.static(__dirname + "/app/img"));    app.use("/css", express.static(__dirname + "/app/css"));    app.use("/partials", express.static(__dirname + "/app/partials"));    app.use("/templates", express.static(__dirname + "/app/templates"));    // any API endpoints    app.post('/api/v1/auth/login', routes.auth.login);    // serve index.html for all remaining routes, in order to leave routing up to angular    app.all("/*", function(req, res, next) {        res.sendfile("index.html", { root: __dirname + "/app" });    });