node.js ExpressJS 3.0 如何将 res.locals 传递给玉石视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12550067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:20:40  来源:igfitidea点击:

ExpressJS 3.0 How to pass res.locals to a jade view?

node.jssessionexpressresponsepug

提问by aeyang

I want to display a flash message after a user fails to sign in but I just can't get the variables to show up in my Jade views.

我想在用户登录失败后显示一条 Flash 消息,但我无法让变量显示在我的 Jade 视图中。

I have some pieces, I know I have to use this in my app.configure():

我有一些片段,我知道我必须在 app.configure() 中使用它:

    app.use (req, res, next) ->
      res.locals.session = req.session

And I'll set what the flash message is after the user POSTS the wrong password:

在用户发布错误密码后,我将设置 Flash 消息的内容:

     exports.postSession = (req, res) ->
       users = require '../DB/users'
       users.authenticate(req.body.login, req.body.password, (user) ->
       if(user)
         req.session.user = user
         res.redirect(req.body.redirect || '/')
       else
         req.session.flash = 'Authentication Failure!'
         res.render('sessions/new', {title:'New', redirect: req.body.redirect })
      )

I don't know how to access res.locals.sessionin my Jade file. I doubt I am setting everything up right. This question is a lot like this one: Migrating Express.js 2 to 3, specifically app.dynamicHelpers() to app.locals.use?but I still can't get it to work. It would be much appreciated if someone could show me just a simple example of setting values in res.local and accessing them in a view.

我不知道如何访问res.locals.session我的 Jade 文件。我怀疑我是否正确设置了一切。这个问题很像这样一个:Migrating Express.js 2 to 3,特别是app.dynamicHelpers() to app.locals.use? 但我仍然无法让它工作。如果有人能向我展示一个在 res.local 中设置值并在视图中访问它们的简单示例,我将不胜感激。

p.s. I do know about connect-flash but I need to understand how to make things available in views.

ps 我确实知道连接闪存,但我需要了解如何在视图中提供可用的东西。

This is my app:

这是我的应用程序:

app.configure(() -> 
  app.set('views', __dirname + '/views')
  app.set('view engine', 'jade')
  app.use(express.bodyParser())
  app.engine('.jade', require('jade').__express)
  app.use(express.methodOverride())
  app.use(express.cookieParser())
  app.use(express.session({ store: new express.session.MemoryStore({reapInterval: 50000 * 10}), secret: 'chubby bunny' }))
  app.use(express.static(__dirname + '/public'))
  app.use((req, res, next) ->
    res.locals.session = req.session
    next()
  )
  app.use(app.router)
)

回答by zemirco

Just to give a short summary for everyone who has the same problem and got the impression that is was solved changing res.redirect.

只是为了给每个有同样问题并得到解决的印象的人做一个简短的总结res.redirect

It is very important to put your app.usemiddleware beforeapp.router. See the comments by TJ Holowaychuck, the author of express

它是把你的非常重要app.use的中间件之前app.router。请参阅 express 的作者 TJ Holowaychuck 的评论

Here is an example using a fresh installation of express v3.0.0rc4

这是一个使用 express v3.0.0rc4 全新安装的示例

app.js:

应用程序.js:

app.use(function(req, res, next){
  res.locals.variable = "some content";
  next();
})

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

index.jade:

index.jade:

extends layout

block content
  h1= title
  p Welcome to #{title}
  p= variable

回答by Adam Albright

If you are using express.session() you must call your function AFTERexpress.session()but BEFOREapp.router, inside of app.configure().

如果您正在使用express.session(),则必须调用函数express.session() ,但app.router,app.configure内()。

app.js

应用程序.js

app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session());

  // Give Views/Layouts direct access to session data.
  app.use(function(req, res, next){
    res.locals.session = req.session;
    next();
  });

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

index.jade

索引.jade

extends layout

block content   
  h1= title   
  p My req.session.var_name is set to #{session.var_name}