Reputation: 10219
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?
Upvotes: 2
Views: 1595
Reputation: 38781
They do not have global scope.
The route takes a handler function for each route. That route is passed the req
and res
objects.
app.get('/my-route', myHandler);
Your handler receives those objects and uses them.
exports.myHandler = function(req, res) {
res.send("Hello world");
);
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?
Upvotes: 6