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?
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" });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With