Re: implementation of routing

98 views
Skip to first unread message

tjholowaychuk

unread,
Oct 16, 2012, 12:29:50 PM10/16/12
to Express
that's a bit of a gotcha right now (having to move .use() up) because
of the reason
you mention with mounting the router on the first app.VERB() call.
I've played with
making each app.VERB() call its own separate middleware so that you
can add
middleware in-between, it does work however it's significantly slower.
Moving it
above will have the correct effect but I definitely agree from a
modularity stand-point
it's not the best, I'd like to revisit routes-as-middleware in the
future. Note though you
can also mount entire apps, which would give you this behaviour

On Oct 16, 9:23 am, craigyk <crai...@nimgs.com> wrote:
> I think I figured out the hard way recently that there is a magical piece
> of middleware called router that get activated on assigning the first
> handler on an express app.  I was trying to keep my routes grouped together
> for organization by truing to assign route specific middleware to a url
> before attaching all the handlers.  I'm a bit confused as to why routing
> was designed this way?  Any pointers on good ways to group handlers and
> specific middleware?  Am I just "doing it wrong"?
>
> I wanted to do something like:
>
> app.use '/client', clientlogin
> app.get '/client/posts/:postid', ....
> app.post '/client/posts/', ...
>
> app.use '/admin', adminlogin  # <- doesn't work unless I move it up top...
> app.get '/admin/users/:userid', ....
> app.del '/admin/users/:userid', ....

Jeff Schwartz

unread,
Oct 17, 2012, 12:28:24 PM10/17/12
to expre...@googlegroups.com
Unless I am misunderstanding your problem domain I think you are wrong in your assumption that in order to use route specific middle ware that you first have to declare it using app.use. I don't in my apps and in fact my routing is highly modularized and using various route specific middleware depending on the problem domain. See my article @ http://jefftschwartz.wordpress.com/2012/09/10/taming-those-unruly-routes/ for a more complete example of how I approach routing and modularization.

Jeff Schwartz

unread,
Oct 17, 2012, 12:33:59 PM10/17/12
to expre...@googlegroups.com
Sorry but I failed to include this link in with my response, http://jefftschwartz.wordpress.com/2012/08/23/use-express-route-specific-middleware-to-access-mongodb/ and it along with the other article whose link I provided describe my approach to modularization and route specific middleware.

Jeff Schwartz

unread,
Oct 17, 2012, 12:36:53 PM10/17/12
to expre...@googlegroups.com
So the crux of it is that you don't need to call app.use, you just need to require your middle ware in the modules you will use them in.
Reply all
Reply to author
Forward
0 new messages