简体   繁体   中英

Variable Scope in node.js/express.js

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM