node.js - Express,Handlebars 显示 flash 信息

标签 node.js express handlebars.js

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

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

在 route 我得到了这个:

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
    }));

然后渲染我的 Handlebars 模板,

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' });
    })

问题是,当输入错误的密码时,闪现消息不会按要求显示。

编辑:我的快速设置是:

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);
});

最佳答案

顺便说一句,我是这样解决的: ...

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

... 将消息编码为 JSON。 然后在我得到的 route :

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' });
    })

然后在我的 Handlebars 模板中:

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

关于node.js - Express,Handlebars 显示 flash 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25564123/

相关文章:

javascript - 生产和 express 中workbox vuejs的路由问题

javascript - 如何使用 testEnvironment 作为 NodeEnvironment 启动快速服务器?

javascript - 从简单的 Backbone 到 Marionette

node.js - Handlebars 中的动态部分

node.js - nodejs ExpressJs BackboneJs Pushstate

javascript - 在 Node Js 上运行服务器时未定义套接字

javascript - 访问 JSON 对象中的值

javascript - 如何在 Puppeteer 上跟踪弹出模式

javascript - 流模式下的流子进程输出