It seems that the req and res variables have global scope in Express (e.g. these variables are accessible regardless of the function scope). How is this achieved without causing collisions between simultaneous clients?
            Asked
            
        
        
            Active
            
        
            Viewed 1,561 times
        
    2
            
            
         
    
    
        David Jones
        
- 10,117
- 28
- 91
- 139
1 Answers
6
            They do not have global scope.
Route
The route takes a handler function for each route.  That route is passed the req and res objects.
app.get('/my-route', myHandler);
Handler
Your handler receives those objects and uses them.
exports.myHandler = function(req, res) {
    res.send("Hello world");
);
Closures
When you make a database call (or any other io bound call) you pass it a callback.  The req and res objects live in that callback as a closure.
exports.myHandler = function(req, res) {
  var weekday = req.query.weekday || "today";
  db.getWeather(weekday, function(err, result) {
    // `res` here is a closure
    if(err) { res.send(500,"Server Error"); return; }
    res.send(result);
  });
};
More about closures: How do JavaScript closures work?
 
    