我目前正在尝试使用connect flash构建一个应用程序,以保存使用会话从一条路由到另一条路由的数据(或者至少据我所知(。
有问题的应用程序在本地上按预期工作,但一旦我部署它,我就会收到一个错误,即flash对象返回时未定义。
我已经尽可能地把它去掉了。我的app.js如下。
var express = require('express')
, flash = require('connect-flash')
, util = require('util');
var app = express();
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('trust proxy', 1);
app.use(express.logger());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({
key: 'sid',
cookie: { maxAge: 60000 }
}));
// Use connect-flash middleware. This will add a `req.flash()` function to
// all requests, matching the functionality offered in Express 2.x.
app.use(flash());
app.use(app.router);
});
app.get('/', function(req, res){
res.render('index', { message: req.flash('info') }); //here I pass the flash object to the view
});
app.get('/scrape', function(req, res){
req.flash('info', 'Hi there!')
res.redirect('/');
});
app.get('/no-flash', function(req, res){
res.redirect('/');
});
app.listen(process.env.PORT);
我唯一的视图有以下代码。
<!DOCTYPE html>
<html>
<head>
<title>Express 3.x Example for connect-flash</title>
</head>
<body>
<p>
<a href="/scrape">Scrape</a> |
<a href="/no-flash">No Flash</a>
</p>
<% if (message) { %>
<p><%= message %></p>
<% } %>
</body>
</html>
此代码取自connect flash 文档中给出的示例
我有一种感觉,我可能需要做一些额外的配置,非常感谢任何帮助。
编辑:奇怪的是,req.flash似乎持续存在,但其内容却没有。
重定向控制台之前的req.flash日志给出:
: [Function: _flash]
重定向后,它产生:
: [Function: _flash]
然而,我将其设置为的info flash对象具有以下行为。
之前:
[Hi there!]
之后:
: []
调试它的第一步是在localhost和生产中简单地控制台.log(req(,看看这两个环境是否都有一个flash属性附加到req。