表达3.0如何使用app.locals.use和res.locals.use

coo*_*ool 6 node.js express

我在express3.0rc2上.如何使用app.locals.use(它是否仍然存在)和res.locals.use

我看到了这个https://github.com/visionmedia/express/issues/1131但是app.locals.use引发了一个错误.我假设一旦我将该函数放在app.locals.use中,我就可以在路由中使用它.

我想补充一下

app.locals.use(myMiddleware(req,res,next){res.locals.uname = 'fresh'; next();})  
Run Code Online (Sandbox Code Playgroud)

然后在任何路由中调用此中间件

谢谢

Cas*_*ter 10

我正在使用Express 3.0,这对我有用:

app.use(function(req, res, next) {
  res.locals.myVar = 'myVal';
  res.locals.myOtherVar = 'myOtherVal';
  next();
});
Run Code Online (Sandbox Code Playgroud)

然后,我有访问myVal,并myOtherVal在我的模板(或直接通过res.locals).

  • 我对"我可以访问**myVal**和**myOtherVal**"这句话感到困惑,因为我认为这意味着你可以做一些像`myVar + ='anotherString'`这样的事情,但实际上你仍然必须有**res.locals.**部分,即`res.locals.myVar + ='anotherString'.然后它会工作 (2认同)

zem*_*rco 8

如果我理解正确,您可以执行以下操作:

app.configure(function(){
  // default express config
  app.use(function (req, res, next) {
    req.custom = "some content";
    next();
  })
  app.use(app.router);
});

app.get("/", function(req, res) {
    res.send(req.custom)
});
Run Code Online (Sandbox Code Playgroud)

您现在可以在每个路由中使用req.custom变量.确保将app.use功能放在路由器之前!

编辑:

好的下一次尝试:)你可以使用你的中间件并在你想要的路线中指定它:

function myMiddleware(req, res, next) {
    res.locals.uname = 'fresh';
    next();
}

app.get("/", myMiddleware, function(req, res) {
    res.send(req.custom)
});
Run Code Online (Sandbox Code Playgroud)

或者你可以"全局"设置它:

app.locals.uname = 'fresh';

// which is short for

app.use(function(req, res, next){
  res.locals.uname = "fresh";
  next();
});
Run Code Online (Sandbox Code Playgroud)