29

I am totally new to everything Nodejs/express/angular, and I just ran into a question that bothers me.

When you have a MEAN stack, it seems that routes can be handled by both Express.js and Angular.

Angular:

For instance, if I define a route in Angular, I can do it like this:

var app = angular.module("app", []).config(function($routeProvider) {
    $routeProvider.when('/login', {
        templateUrl: '/templates/login.html',
        controller: 'LoginController'
    });

    $routeProvider.when('/front', {
        templateUrl: '/templates/front.html',
        controller: 'FrontController'
    });


    $routeProvider.otherwise({redirectTo: '/front'})
});

But with express.js I do:

app.get('/',function(req,res){
    res.sendfile('templates/angular.html');
});

So my question is:

When do you use angular routing, and when do you use express routing?

(I might miss something very obvious here, but I hope you can point it out)

Lars Holdgaard
  • 9,496
  • 26
  • 102
  • 182

1 Answers1

49

Those two serve different purposes on a single page app.

The app would do all the CRUD (endpoints where you create/read/update/delete your stuff, for example: projects, users, bills, etc). Also it would do all the authentication stuff (like /login and /register).

All of that needs routes, because you would want something like /api/users to grab all your users. All those routes, AKA CRUD routes and authentication routes goes into express.js router. Why there? Because those are routes of the backend.

On the other hand, you have your angular application, which contains the visual part of your application and there you want some routes. You want / to point to your home, you would want /users to have a page where you list your users or even /users/add to have a page with a form to add new users.

You could see it this way:

Backend routes (express ones): Those are the routes that an end user won't have to know about or even use them (your angular app will use them to communicate with the backend to work with its data but an end user wouldn't put them directly on the browser)).

Frontend routes (angular ones): Are the routes that maps to different pages of your application and because of that, end users can use them to access some parts of your application directly.

Jesus Rodriguez
  • 11,918
  • 9
  • 64
  • 88
  • Express.js can handle rendering template apart from just crud so than it means angular is of no use. E.g. in PHP I can use Slim Framework to just write api routes or I can create a full web application using it. – Mohammad Sharaf Ali Jun 09 '16 at 17:48
  • Its an old answer, but anyway. What would be the best way to hide backend express routes from a user so that when they access those in a browser it will return 404? – mikebrsv Sep 29 '17 at 21:54
  • did you get an answer to your comment @mikebrsv – HexaCrop Aug 20 '19 at 11:08