当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Node + Express: How do the req and res variables have global scope without causing collisions?

问题描述:

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?

网友答案:

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?

分享给朋友:
您可能感兴趣的文章:
随机阅读: