How to access req and res objects in hooks?
-
I would like to ask whether it is possible to access the req and the res objects provided by express .
Essentially I would like to check the http request headers each time before executing a hook.
Thanks in advance.
-
For what hook?
-
@PitaJ I would say any hook. Is there a way to do so?
-
You might be able to use continuation-local storage to do this. If you added a middleware like so:
var cls = require('cls-hooked'); var express = cls.createNamespace('express'); app.use(function (req, res, next) { express.set('request', req); express.set('response', res); express.run(next); });
then you could probably use those later like this:
plugin.addStyleSheet = function (data, next) { var req = express.get('request'); // do something with request next(null, data); };
Beware, I haven't tested any of this. What I wrote may not work at all. It's worth a try. I general, though, I'd recommend using the data you have in the hook itself. There's usually a better way.
-
Interesting. I never knew that such a thing existed (storing at the chain level). I'll post again when I give it a try.
Doing it through the data provided at the hook level is very difficult, because the different hooks (userCreate, ...etc) are executed away from the middleware scope.
Thanks.
-
Yes... adding in continuation local storage is something we really wanted to do, although when @akhoury tried to do it a couple years back, the technology was as-yet still a little immature.
Perhaps it is time for us to take a look at it again