在快速js中为请求对象分配默认值

时间:2013-01-12 14:48:15

标签: node.js express connect

我如何确保特定对象可用于我在快递中处理的每个请求?

var somethingImportant = "really important";
var app = express();

// This is just a hypothetical example of what I'm after...
app.mixThisInWithRequest({
    somethingImportant: somethingImportant
});

app.use(function (request, response, next) {
   console.log(request.somethingImportant);
});

鉴于上面的例子,是否存在类似于mixThisInWithRequest函数的工具?

1 个答案:

答案 0 :(得分:2)

将其添加到中间件中的request对象,就像您需要的app.use链中一样:

var somethingImportant = "really important";
var app = express();

app.use(function (request, response, next) {
    request.somethingImportant = somethingImportant;
    next();
});
app.use(function (request, response, next) {
   console.log(request.somethingImportant);
});