2

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.

2
  • where/how exactly is the 'second part' called? Also am I correct to assume that the second part is the second app.use? Commented Oct 2, 2013 at 23:45
  • @nemo Yeah, they are all in app.js; And the 'second' part is referring to 'app.use(require('./middleware/im')({'... Commented Oct 2, 2013 at 23:47

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.