关于req.flash的问题。
发布于 11 年前 作者 fatelovely 12595 次浏览 最后一次编辑是 8 年前

**express3.x已经废弃了req.flash的这个功能,我看官方文档,是“Removed:req.flash() (just use sessions: req.session.messages = [‘foo’] or similar)”是让我们是用req.session来代替是用req.flash么?我遵循开发指南里面的教程,个人感觉req.flash本身只是一个容器而已,只不过用来存储信息而已。所以我在代码中,凡事需要书中用req.flash存储的信息,我全部用req.session来存储了。比如,req.session.error=’some error‘,然后在app.js中使用这样的代码,app.use(function(req,res,next){ res.locals.user=req.session.user; res.locals.success=req.session.success; res.locals.error=req.session.error; })我以为这样就可以了。但总是提示说模板中的success,user,error无定义。我不能明白这是怎么回事。不是说res.locals里面的变量自动传递给模板引擎吗?

11 回复

你的这个app.use是app.configure 里面么?

根本不需要配置再app.configure里面啊。根据官方文档,app.configure函数只是一个用来配置根据不同环境而调用不同函数的工具而已,推荐不用。app.configure([env], callback) Conditionally invoke callback when env matches app.get('env'), aka process.env.NODE_ENV. This method remains for legacy reason, and is effectively an if statement as illustrated in the following snippets. These functions are not required in order to use app.set() and other configuration methods. // all environments app.configure(function(){ app.set('title', 'My Application'); }) // development only app.configure('development', function(){ app.set('db uri', 'localhost/dev'); }) // production only app.configure('production', function(){ app.set('db uri', 'n.n.n.n/prod'); }) effectively sugar for: // all environments app.set('title', 'My Application'); // development only if ('development' == app.get('env')) { app.set('db uri', 'localhost/dev'); } // production only if ('production' == app.get('env')) { app.set('db uri', 'n.n.n.n/prod'); }

表示 session 我不熟悉… GFM 标记的语法看这里, 英文版… 格式调整下吧 http://github.github.com/github-flavored-markdown/

你模板里是 locals.success 么

res.locals.success.

没接触过marddown,上文的格式确实很挫,下次会注意修改的。

@fatelovely 模板里该写 locals.success

@zs1621 我上面的回答错了。模板里面就是直接引用success啊。为什么要用locals.success?官方文档里面没有这样的说明啊。

@fatelovely locals就相当于你的 res.render('',{title:'主页'}) 里的title success只是locals的其中一个属性而已…

我看别人的代码里面再模板里面都是直接调用变量的。## View options ##

The "view options" setting is no longer necessary, app.locals are the local variables merged with res.render()'s, so app.locals.pretty = true is the same as passing res.render(view, { pretty: true }).

这是express的官方说明啊。

@fatelovely 标记代码在代码块开始的上一行用三个 `, 代码块结束以后换行再用三个 `, 然后中间的代码就标记好了

回到顶部