【问题标题】:Undefined method flash in the view of node.jsnode.js 视图中未定义的方法 flash
【发布时间】:2014-05-28 12:50:43
【问题描述】:

node.js 中查看flash messages 时出现问题@ 在我的控制器中

this.req.flash('info','successfully submited');
this.redirect("/home");

在我的主页视图中,我无法将flash messages 作为

req.flash('info');

编辑 在控制器中

self.req.flash('message','hello');

考虑中

<%= req.flash('message) %>

在 server.js 中

app.configure(function (){

  app.use(express.cookieParser());
  app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
  app.use(passport.initialize());
  app.use(locomotive.session());
  app.use(flash());
  app.use(passport.session());
  app.use(app.router);

  app.dynamicHelpers({ messages: require('express-messages') });
});

我有机车框架。

【问题讨论】:

  • 您的问题中没有足够的信息来提供帮助。您是否正确要求connect-flash?你用app.use(flash)了吗?你还尝试了什么?
  • 是的,我在 server.js 中添加了 app.use(flash) 并且还使用了 connect-flash。当我使用 flash() 时出现问题。错误来自未定义的方法 flash()。
  • 你能发布那个代码吗?如果这是问题所在并且不在问题中,那么我们无能为力提供帮助。 :)
  • 请看我编辑的帖子

标签: node.js locomotivejs node.js-client


【解决方案1】:

请看临时数据示例https://github.com/MKxDev/TempData

var tempData = require('tempdata');
    var app = express();

    app.configure(function() {
        ...

        // This has to appear BEFORE the router
        app.use(express.cookieParser());
        app.use(express.session({ secret: 'your_super_secret_session_key' })); // please change this!
        app.use(tempData);

        ...
    });

    ...

    // Routes
    app.get('/', function(req, res) {
        // Retrieve tempData value here. It won't exist unless the request
        // was redirected
        var tempVal = JSON.stringify(req.tempData.get('test_val'));

        res.render('index', { title: 'Express', temp: tempVal });
    });

    app.post('/', function(req, res) {
      // Set tempData value here
        req.tempData.set('test_val', { x: 'Hello World!' });

        res.redirect('/');
    });

【讨论】:

    【解决方案2】:

    按顺序将您的app.use(flash()) 移到更高的位置...见下文。 Flash 需要在护照之前初始化,以便 Flash 被识别并可供护照使用。

    app.configure(function (){
      app.use(express.cookieParser());
      app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
      app.use(flash()); // moved this up a few lines
      app.use(passport.initialize());
      app.use(locomotive.session());
      app.use(passport.session());
      app.use(app.router);
      app.dynamicHelpers({ messages: require('express-messages') });
    });
    

    【讨论】:

    • 先生,由于未定义的 flash() 方法仍然出现错误
    • 在视图中?啊……首先,您认为有错字吗?关于我没有注意到的观点的问题中有一个错字 - 缺少单引号。其次,您如何将req.flash 传递给视图?您是否在某个时候设置了self = this
    • Matt Bakaitis 是的,我正在设置 self=this 和 req.flash
    猜你喜欢
    • 2022-11-02
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 2023-04-02
    • 2016-10-27
    相关资源
    最近更新 更多