【问题标题】:Error: req.flash() requires sessions错误:req.flash() 需要会话
【发布时间】:2015-08-14 07:29:05
【问题描述】:

我是 node 新手,我很确定我已经设置了中间件和 express 以使用 flash 消息传递,但是我仍然收到错误:

Error: req.flash() requires sessions

设置

//express.js
     var flash = require('connect-flash')

     module.exports = function (app, config, passport) {
         app.use(flash());
     };

//route js
     exports.loginGet = function (req, res) {
       res.render('users/login', {
         title: 'Login',
         message: req.flash('error') //error in question
       });
     };

我还能做些什么来确保我已正确设置所有内容并使其正常工作?

【问题讨论】:

标签: node.js flash express


【解决方案1】:

来自readme(强调我的):

Flash 消息存储在会话中。 首先,通过启用 cookieParser 和会话中间件,像往常一样设置会话。 然后,使用 connect-flash 提供的 flash 中间件。

express-sessions 与 express 4 一起使用,不再需要 cookieParser

var session = require('express-session');

//...


app.use(session({ cookie: { maxAge: 60000 }, 
                  secret: 'woot',
                  resave: false, 
                  saveUninitialized: false}));

【讨论】:

  • 没有使用 express v2 和 3 中的 express.XXX?我认为他们从 express 中删除了这些功能并使其成为单个中间件?
  • 我的错 - 你是对的。我已经相应地更新了我的答案。
【解决方案2】:

请检查 mongodb 连接。可能会出现像“mongoError:拓扑已破坏”这样的 mongo 错误。 要解决此问题,请查看here

【讨论】:

  • 这帮助我修复了由于使用 connect-redis 会话配置错误(错误主机名)导致的相同错误消息
【解决方案3】:

就我而言,问题是 Redis 没有在听。我通过启用logErrors 属性发现了这一点:

new RedisStore({
  host: 'localhost',
  port: '6379',
  logErrors: true,
});

这导致了这样的消息:

Warning: connect-redis reported a client error: Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

【讨论】:

    【解决方案4】:

    我遇到了这些问题,我通过尊重级联来解决它们

    app.use(passport.initialize());
    app.use(passport.session());
    //SESSION FLASH
    app.use(flash());

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多