node.js - connect-flash 返回 req.flash 为未定义
问题描述
我目前正在尝试使用 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 在重定向 console.logged 之前给出:
: [Function: _flash]
在重定向之后它会产生:
: [Function: _flash]
但是,我将其设置为的 info flash 对象具有以下行为。
前:
[Hi there!]
之后:
: []
解决方案
我调试它的第一步是简单地在 localhost 和生产中使用 console.log(req),看看这两个环境是否都有一个附加到 req 的 flash 属性。
推荐阅读
- python - 如何在 Pandas 中绘制和标记多个自相关函数?
- python - 在 Pandas DataFrame 中重新分配最大值
- c++ - 我是初学者,刚开始学习 c++,我在 windows 10 64 位 pc 上使用 eclipse [版本:Helios Service Release 2 Build id:20110218-0911]
- printing - 如何限制 Fortran 中每行打印的字符数?
- ios - 如果要使用主故事板文件,应用程序委托必须实现 window 属性。(迅速)
- java - 在使用嵌套 for 循环时,if 语句是否会等到循环结束后再继续执行 if 语句代码?
- javascript - 将数组中的值放入文本框中
- javascript - 在 Angular 中使用 BehaviourSubject 在两个组件之间进行通信
- domain-driven-design - 工厂模式实现类在 DDD 的干净架构中位于何处
- reactjs - Handling error in React with Formik: Objects are not valid as a React child