I' trying to get AngularJS routes working with my NodeJS http server. I have the following code:
server.js:
app.set('port', 3000);
app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/menuItems', menu.getMenuItems);
httpServer.listen(app.get('port'), function () {
console.log("Express server listening on port %s.", httpServer.address().port);
});
app.js:
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/cases', {
templateUrl: '../templates/cases.html'
}).
otherwise({
templateUrl: '../index.html'
});
}]);
but no matter what I try to do I get "Cannot GET /cases".
I could set up all my routes in node.js but would prefer not to.
What am I doing wrong?
I have looked at this post: How to use AngularJS routes with Express (Node.js) when a new page is requested? but still don't get it :-(
You you have two choices in this case.
The first one is what @majidarif suggested: use your routes in the hash of the URL.
However, in better web applications it's highly desirable to have nice URLs. To solve for this, you could have a default route (or all your frontend routes listed one by one) in the backend, whose handler serves the angular app, i.e.
function sendIndex(req, res) {
res.sendfile(indexPath);
}
app.get('/cases', sendIndex);
Keep in mind that this will potentially break your relative URLs (JS, CSS, images and everything else served by express) so you either use absolute URLs, or use a backend side templating engine to set the base path for relative URLs.
Then, in your angular app the initial route will be handled for you, at least if you've set up the html5 option for the $location service (good read for this case, by the way).