Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

express.js object values remain/persist between requests, require() cache?

express.js object values remain/persist between requests, require() cache?

Problem

I'm fairly new to node/express but love it so far.

One thing I've noticed after writing a few apps now, is that property values of the Request object will sometimes persist between requests within required modules; and not necessarily from the same IP or even browser.

Take for example, this super simple GET request:

GET /lookup/?first=ben&last=ipsen

Which gets handled something like this:

app.get('/lookup/', function(req, res){ 
     lookup = require('lookup')
     lookup.find_user(req, res, function(err, user){
        if(err) throw new Error(err) 
        res.send(user) 
     });

 });

Obviously, this works well and life is great. However... If a second request is received with empty or absent values, say:

 GET /lookup/?first=

app.get('/lookup/', function(req, res){ 
     lookup = require('lookup')
     lookup.find_user(req, res, function(err, user){
        if(err) throw new Error(err) 
        // user.first = ben 
        // user.last = ipsen !?
        res.send(user) 
     });

 });

Is this an issue caused by the require cache and not express' fault? Am I making a mistake by loading a modules within a request? There are many cases where I want to load a specific module based on the request but I can live without that 'require'ment.. har.

I'm surely experiencing some novice issues here, but as always any guidance is appreciated!

Problem courtesy of: benipsen

Solution

There is no problem with the require() cache. It's only going to return the same object every time, and there is nothing wrong with this.

I suspect the problem is your lookup module. You've probably defined a variable globally or forgot to use var in front of it.

Solution courtesy of: Brad

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

express.js object values remain/persist between requests, require() cache?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×