3

I have read several other answers on this topic, but I do not fully understand how this works. I have an angular front-end. I am trying to use $routeProvider to load partials into my page for a single page application. I am getting 404 for the $routeProvider requests and I think there must be a way to set this up without declaring a route for every partial on the server. There will be many more partials soon even though I only have one declared in my config right now. My routeProvider code looks like this:

myApp.config(['$routeProvider',
function ($routeProvider) {
    $routeProvider.
        when('/register', {
            templateUrl: 'partials/register',
            controller: 'registerCtrl'
        })
}])

but going to localhost:3000/register gives a 404 error. I looked at this response on SO as well as some others, but I have not been able to put all the pieces together.

Express 4, NodeJS, AngularJS routing

How is this solution from the above post

app.use('/*', function(req, res){
    res.sendfile(__dirname + '/public/index.html');
});

able to find the partials and return them to the front end (btw this snippet did not work for me).

My app isn't much different than creating a new express app with express generator. I have these require and use statements related to routing:

var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);

and this route to serve my home page in routes/index:

router.get('/', function(req, res, next) {
  res.render('home');
});
Community
  • 1
  • 1
user137717
  • 2,005
  • 4
  • 25
  • 48

1 Answers1

3

When you use front-end routing you don't have to declare a route for every partial on the server. The simplest form of the solution is to let the user hit any route with a wildcard match on the back, and no matter what route they're viewing you just serve up the same front end application template. So in fact you for the most part do away with backend routing altogether. Once your JS kicks in and reads the current route out of the navbar, it will resolve the appropriate view.

Check out one of the tutorials for how to configure your express backend to handle this: http://fdietz.github.io/recipes-with-angular-js/backend-integration-with-node-express/implementing-client-side-routing.html

There's some nuance and previously there was controversy around this structure because of things like SEO, but a lot of that has been cleared away by Google now being able to parse JS and resolve the view in SPAs (http://googlewebmastercentral.blogspot.com/2014/05/understanding-web-pages-better.html)

Of course, you will actually have some routes on the backend in order to accept api requests, but ideally that's it unless you choose to get fancy and go isomorphic, prerendering the js on the backend and serving a completed view (though that's better suited in React for now, at least until Angular 2.0)

wesww
  • 2,863
  • 18
  • 16