首页 > 解决方案 > 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!]

之后:

: []

标签: node.jsexpressexpress-session

解决方案


我调试它的第一步是简单地在 localhost 和生产中使用 console.log(req),看看这两个环境是否都有一个附加到 req 的 flash 属性。


推荐阅读