Reputation: 45
I'm using express/node now and I have the following
app.use(useridDetect);
function useridDetect (request, response, next) {
var myurl = url.parse(request.url);
if (myurl.pathname === "/cookie") {
var i = request.url.indexOf('?');
query = request.url.substr(i+4, 32);
//set userid
next();
} else {
next(); // keep the middleware chain going
}
}
app.use(require('./middleware/im')({
userid: query,
maxAge: 30 * 1000,
reapInterval: 20 * 1000,
authentication: require('./libs/authentication/' + AUTH_LIBRARY)
}));
Now it says query is undefined in the second part(Obvious I can't do this...) But how can I make the second function access that variable without using global variable? Since I will have multiple people using this script and too many global vars might be a bad idea.
Upvotes: 2
Views: 1865
Reputation: 13293
Each middleware that you define gives you a chance to read request information and modify the request/response objects. Rather than setting a variable called query, you should add a query
field to you request object, and then have middleware/im
's request handler look for that field in the request object.
However, note that Express already does query string parsing for you[1], so you shouldn't even need the userIdDetect
middleware function. Just have middleware/im
's request handler look in the object in `req.query, which should already contain a field named whatever the query string parameter was named.
[1] http://expressjs.com/api.html#req.query
Upvotes: 1