I'm using a nodeJS server with Express to serve my AngularJS application. This all works fine when I'm using angularJS default routes (hashbangs), but now I'm trying to activate html5 mode.
I'm activating html5mode like this:
$locationProvider.html5Mode(true).hashPrefix('!');
And this is what my nodeJS app.js
file looks like:
var path = require('path'),
express = require('express'),
app = express(),
routes = require(path.join(__dirname, 'routes'));
app.configure(function() {
app.use(express.logger('dev'));
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.all("/*", function(req, res, next) {
res.sendfile("index.html", { root: __dirname + "/../app" });
});
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
However, this now serves all requests as my index.html
file, and so I get the following error from requireJS:
Uncaught SyntaxError: Unexpected token <
I tried adding the following to my nodeJS app.js
so it would serve my resources correctly:
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"));
but still no luck.
I also tried replacing the app.all
statement with:
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/../app/index.html');
});
but that didn't work either. What can I do to get angularJS html5mode working with nodeJS and Express? Thanks.
Uncaught SyntaxError: Unexpected token <
because the path was not being found as expected. Instead of serving back the Javascript (or CSS, etc.) file you wanted, the 'catch all /*' route was being triggered and sending back the HTML instead.Uncaught SyntaxError: Unexpected token <
is caused because your angular js app file is not being loaded. Check the routes to your js directory. You will probably want to change them from/
to/public
or to some other name which is more unique than/