Which should come first?

1,202 views
Skip to first unread message

Paul Vencill

unread,
Jun 7, 2012, 11:21:26 AM6/7/12
to expre...@googlegroups.com
So, I had thought that if you apply middleware, it fires in order.  But it looks like some of my middleware is firing late.  eg:

app.use(loadViewdata);

app.get('/', doSomethingWithViewData, routes.index);


In this example, I would expect "loadViewdata" to run before "doSomethignWithViewData", but that's not happening, even though I'm using next() as intended.  

If I apply loadViewdata as a route middleware:

app.get('/', loadViewdata, doSomethingWithViewData, routes.index);


all works as expected but I was trying to have it apply to all routes, rather than repeating myself.  What am I missing?

Thanks,
Paul

tjholowaychuk

unread,
Jun 7, 2012, 12:59:08 PM6/7/12
to Express
the one key thing you have to remember (currently), is that all of the
routes (app.get, app.put, etc)
are part of a routing middleware called app.router (this is an
instance of a Router). So app.use()
works with individual middleware, so if you call it between two
app.get() calls for example it's
not actually added between them.

so you might want to do something like:

app.use(loadViewData);
app.use(app.router);

app.get('/.....

that way it's before the routes.

I should note that I've played with each app.{get,put,...}() call
being its
own middleware, which is nice in a lot of ways but I need to improve
the
performance of that solution before considering it

Paul Vencill

unread,
Jun 7, 2012, 1:09:15 PM6/7/12
to expre...@googlegroups.com
Hm.  ok, so I am doing my routes in a separate file and was calling those app.use(middleware) statements in *that* file, are you saying that that means they fire after the express router middleware?  That makes more sense, now, thanks.

--
You received this message because you are subscribed to the Google Groups "Express" group.
To post to this group, send email to expre...@googlegroups.com.
To unsubscribe from this group, send email to express-js+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/express-js?hl=en.


Reply all
Reply to author
Forward
0 new messages