Express.js or angular for handling routes in a MEA

2019-03-08 10:03发布

问题:

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)

回答1:

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.