Node.js + Express: Routes vs controller

node.jsExpress

node.js Problem Overview


New to Node.js and Express, I am trying to understand the two seems overlapping concepts, routes vs controller.

I have seen examples that simple does app.js + routes/*, this seems to be sufficient to route various requests needed.

However, I also see people talking about using controllers, and some that implies a more formal MVC model (???).

Would be great if someone can help me clear this mystery, and if you have a good example for setting up controller in Node.js + Express framework that will be great!

Thanks,

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1462192View Question on Stackoverflow
Solution 1 - node.jsMichelle TilleyView Answer on Stackoverflow
Solution 2 - node.jsuser8762553View Answer on Stackoverflow