Navigate back to the homepage

Using Express Router instead of express-namespace

Bulkan Evcimen
June 9th, 2014 · 1 min read

Photo by Webaroo on Unsplash

express 4.0 has been out for a while and it seems people are still using express-namespace. According to npm it had 183 downloads on the 8th of June.

express-namespace hasnt been updated in nearly two years and it can now be replaced with the Router that comes with express 4.

Also I’ve found that the middleware mounting on namespace roots would mount it at the the application level. This is else that the router solves as it allows you to seperate out routes into different modules with its own middleware.

Here is the example from express-namespace written using the Router in express 4.0.

1var express = require('express'),
2 forumRouter = express.Router(),
3 threadRouter = express.Router(),
4 app = express();
5
6forumRouter.get('/:id/((view)?)', function(req, res){
7 res.send('GET forum ' + req.params.id);
8});
9
10forumRouter.get('/:id/edit', function(req, res){
11 res.send('GET forum ' + req.params.id + ' edit page');
12});
13
14
15forumRouter.delete('/:id', function(req, res){
16 res.send('DELETE forum ' + req.params.id);
17});
18
19app.use('/forum', forumRouter);
20
21threadRouter.get('/:id/thread/:tid', function(req, res){
22 res.send('GET forum ' + req.params.id + ' thread ' + req.params.tid);
23});
24
25forumRouter.use('/', threadRouter);
26
27app.listen(3333);

A little bit more typing but easier to explain to others and no monkey patching weirdness of express-namespace.

The routes are more little more explicitly defined.

Hope this helps.

More articles from Bulkan

AngularJS & Popup Windows

Photo by Sergi Ferrete on Unsplash Popup windows are extremely annoying hence most modern browsers block them, agreeably so. That being said…

April 14th, 2014 · 1 min read

Using Sequelize Migrations With An Existing Database

Photo by Kolar.io on Unsplash Install Im sure you know know how to install packages but here is the command for the sake of completeness npm…

January 20th, 2014 · 1 min read
© 2007–2020 Bulkan
Link to $https://twitter.com/bulkanevcimenLink to $https://github.com/bulkanLink to $https://instagram.com/bulkan.evcimen