Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS routing in ExpressJS

I have an AngularJS app on a NodeJS server with ExpressJS. Now I am serving an Angular app as static files:

app.use(express.static(__dirname + '/app'));

But in navigation, I have a # sign:

http://127.0.0.1:8080/#/queryes

To solve this problem, I put this code in the Angular Router:

$locationProvider.html5Mode(true);

But now I can't get partial views. How do I mix Angular Routes with ExpressJS?

like image 884
Norbert Pisz Avatar asked Dec 05 '13 10:12

Norbert Pisz


1 Answers

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" });
    });
like image 198
Jakemmarsh Avatar answered Sep 28 '22 09:09

Jakemmarsh