Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js + Express: Routes vs controller

People also ask

Are controllers the same as routes?

"Routes" to forward the supported requests (and any information encoded in request URLs) to the appropriate controller functions. Controller functions to get the requested data from the models, create an HTML page displaying the data, and return it to the user to view in the browser.

What is the difference between controller and middleware?

As a rule of thumb, middleware are often reused more than once and often they do not response. On contrary, controller respond and are most of the time specific to one endpoint. 'Controllers' aren't first order components of node/express. They are project artifacts if defined as such.

Why we use routing in Express JS?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express.


One of the cool things about Express (and Node in general) is it doesn't push a lot of opinions on you; one of the downsides is it doesn't push any opinions on you. Thus, you are free (and required!) to set up any such opinions (patterns) on your own.

In the case of Express, you can definitely use an MVC pattern, and a route handler can certainly serve the role of a controller if you so desire--but you have to set it up that way. A great example can be found in the Express examples folder, called mvc. If you look at lib/boot.js, you can see how they've set up the example to require each file in the controllers directory, and generate the Express routes on the fly depending on the name of the methods created on the controllers.


You can just have a routes folder or both. For example, some set routes/paths (ex. /user/:id) and connect them to Get, Post, Put/Update, Delete, etc. and then in the routes folder:

const subController = require('./../controllers/subController');

Router.use('/subs/:id');

Router
 .route('subs/:id')
 .get(subController.getSub)
 .patch(subController.updateSub);

Then, in the controllers folder:

exports.getSub = (req, res, next) => {
  req.params.id = req.users.id;
};

Just to make something. I've done projects with no controllers folder, and placed all the logic in one place.