Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice for handling routes in expressJS [closed]

I was used to write routes like this with ExpressJS:

var app = express();
app.get('/something', function(req, res){});

But I have seen with the all new v4 of ExpressJS that we can now use express.router() like a middleware like this:

var app = express();
var router = app.Router();
app.use(router);

router.get('/something', function(req, res){});

So my question is, what's the real difference between the two and what's the best practice ?

Thank you in advance!

like image 480
Marc Delalonde Avatar asked Jan 31 '26 03:01

Marc Delalonde


2 Answers

I think this is really just a matter of preference. Personally I prefer the original way you noted above, since I can keep the routes with the code that should be run (I generally pull this logic into separate files):

app.js (similar to this: https://gist.github.com/dylants/6705338)

// ...

// pull in all the controllers (these contain routes)
fs.readdirSync("controllers").forEach(function(controllerName) {
    require("./controllers/" + controllerName)(app);
});

// ...

controllers/my-controller.js

module.exports = function(app) {
    app.get("/api/my-uri", function(req, res) {
        // ...
    });
};

Again, doing this allows me to control the URIs within the separate files themselves, so folks are able to work isolated. That said, others prefer to have all the routes within the same file, so they can be viewed all at once (similar to the way Rails has a route command). Probably best to consult with the members of your team and see which they prefer.

like image 159
dylants Avatar answered Feb 01 '26 17:02

dylants


Difference in code organization.

Using router.route() is a recommended approach to avoiding duplicate route naming and thus typo errors.

Mount in, testing so easy with this syntax:

router
  .route('/')
   .all(function(req,res,next){ next(); })   
   .get(...)
   .post(...)
   .put(...)
   .delete(...) 

 router.param('id',function(req,res,next,id){ ... })     
 router.use('/feedback', anotherSubRouter); // will /my-mount-point/feedback

 ... somewhere in app

 app.use('/my-mount-point', router);
 app.use('/api', apiRouter);

 ...etc

Official docs here

like image 21
diproart Avatar answered Feb 01 '26 18:02

diproart