Reputation:
Why would I do:
var router = express.Router();
router.get('/', ...)
instead of
app.get('/', ...);
The two will give me the same result. What's the point of instantiating a router if app is already a router?
Upvotes: 7
Views: 237
Reputation:
It's useful if you're writing a very complex app. For example, you might have a tree like this:
routes
user.js
post.js
server.js
In both user.js
and post.js
, you would create a Router
object and export it. You can attach all the routes for the user to that router - say /user/new
, /user/edit
, and /user/1
, and /post/new
, /post/edit
, and /post/1
.
In server.js
, you would require
each of your routes and attach their routers via app.use
:
app.use('/user', user);
app.use('/post', post);
All requests to /user
will then be sent to the user router, and all requests to /post
will be sent to the post router. Then, you can register routes like:
router.get('/new', function(req, res) { });
And it will automatically be mapped to /user/new
or /post/new
. This is useful because it helps organize your app, and it forces you to segregate one section of your application into one file (separation of concerns and all that). It's a useful part of express that isn't very well advertised.
Upvotes: 4
Reputation: 10211
Revisiting the router middleware
The router middleware is very special middleware. While other Express middlewares are inherited from Connect, router is implemented by Express itself. This middleware is solely responsible for empowering Express with Sinatra-like routes. The router middleware is a middleware system of its own. The route definitions form the middlewares in this stack. Meaning, a matching route can respond with an HTTP response and end the request flow, or pass on the request to the next middleware in line.
and then
To ensure predictability and stability, we should explicitly add router to the middleware stack
app.use(app.router);
Upvotes: 1