7

私は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();})  

そして、任意のルートでこのミドルウェアを呼び出します

ありがとう

4

2 に答える 2

11

私はExpress 3.0を使用していますが、これは私にとってはうまくいきます:

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

myValその後、myOtherValテンプレートに (または を介し​​て直接)​​ アクセスできますres.locals

于 2012-09-24T19:39:10.907 に答える
9

私があなたを正しく理解していれば、次のことができます:

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)
});

すべてのルートで req.custom 変数を使用できるようになりました。app.use 関数をルーターの前に置いてください。

編集:

次に試してみてください:)ミドルウェアを使用して、必要なルートで指定できます。

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

app.get("/", myMiddleware, function(req, res) {
    res.send(req.custom)
});

または、「グローバル」に設定できます。

app.locals.uname = 'fresh';

// which is short for

app.use(function(req, res, next){
  res.locals.uname = "fresh";
  next();
});
于 2012-09-24T19:23:45.627 に答える