【问题标题】:Express, Handlebars show flash messagesExpress、Handlebars 显示闪烁信息
【发布时间】:2014-10-23 05:17:15
【问题描述】:

我将 Node 与 express 和车把一起使用。我有一个登录表单,应该向用户显示登录错误消息。我的代码如下: 验证(使用护照):

...
else if (password != user.password) {
            return done(null, false, req.flash('message', 'Wrong password'));
...

在路线中我得到了这个:

app.post('/sign-in', passport.authenticate('local', {
        successRedirect : '/', // redirect to the home page
        failureRedirect : '/sign-in', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

然后渲染我的车把模板,

app.get('/sign-in', function(req, res) {
        res.render("signin.handlebars", {layout: 'users.handlebars', action: 'Sign in', message: req.flash('message'),
                    csrf: 'CSRF token goes here' });
    })

问题是,当输入错误的密码时,flash message 没有按要求显示。

编辑:我的快速设置是:

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('models', __dirname + '/models');
app.use(express.static(__dirname + '/public'));     // set the static files location /public/img will be /img for users
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere', resave: true, 
                        saveUninitialized: true, }));
app.use(passport.initialize());
app.use(passport.session());
//app.use(session({ store: new RedisStore }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(flash());
app.use(morgan("dev"));
app.disable('x-powered-by');
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
});

【问题讨论】:

  • 你安装了 express-flash 吗?
  • 我正在使用 connect-flash
  • 你有没有在其他路由中尝试过简单的闪信?
  • Yap...其他页面上也没有显示任何内容。我上面的代码正确吗?
  • 我注意到的第一件事是你的错误中间件只是设置一个状态,从不发送响应。

标签: node.js express handlebars.js


【解决方案1】:

我是这样解决的: ...

if (!user) {
            return done(null, false, {
                message: 'The email you entered is incorrect'
            });

... 这会将消息编码为 JSON。 然后在我得到的路线中:

app.get('/sign-in', function(req, res) {
        res.render("signin.handlebars", {layout: 'users.handlebars', action: 'Sign in', ***error: req.flash('error')***,
                    csrf: 'CSRF token goes here' });
    })

然后在我的车把模板中:

{{#if error}}
    <div class="alert alert-danger">{{error}}</div>
{{/if}}

【讨论】:

    【解决方案2】:

    您需要在 index.js 中添加一个全局变量

    app.use((req, res, next)=>{
      app.locals.success = req.flash('success')
      next();
    });
    

    然后在您的路线中添加消息

    req.flash("success", "Your message");
    

    你终于.hbs

    {{#if success}}
    {{success}}
    {{/if}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 2018-07-06
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多