我将 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/