会话Flash消息仅在单独刷新后显示,而在Express中不显示 [英] Session flash messages only showing after a separate refresh and not on POST in express

查看:79
本文介绍了会话Flash消息仅在单独刷新后显示,而在Express中不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几周前从Express开始,终于遇到了我的第一个障碍.我试图弄清楚如何向我的视图(layout.jade)发送即时消息.当我正在验证用户注册并且验证失败(使用express-validator)时,我想写入会话Flash消息,然后在页面上显示它.

Started with Express a couple weeks ago and finally hit my first roadblock. I'm trying to figure out how to send a flash message to my view (layout.jade). When I'm validating a user signup and it fails validation (using express-validator), I want to write to the session flash message and then show it on the page.

我现在正在做的事情只有在发布后刷新(例如在controllers/index.js中)时才有效,并且我还需要弄清楚如何仅使此Flash消息显示一次:

What I'm doing now only works if I refresh AFTER POSTing (e.g. in controllers/index.js), and I also need to figure out how to only make this flash message show once:

/app.js

/*
 * Configuration
 */
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(expressValidator);
  app.use(express.cookieParser());
  app.use(express.bodyParser({ uploadDir : './' }));
  app.use(express.methodOverride());
  app.use(viewHelpers());
  app.use(function(req, res, next){
    res.locals.messages = req.session.messages || {};
    delete req.session.messages;
    next();
  });
  app.use(express.session({
    secret: config.secret,
    cookie: {
      maxAge: 365 * 24 * 60 * 60 * 1000
    },
    store: new MongoStore(config.db)
  }));
  app.use(express.static(__dirname + '/public'));
  app.use(app.router);
});

/views/layout.jade:

/views/layout.jade:

div.alert.alert-error
  - if (typeof messages !== "undefined")
    !=partial('session_flash', { messages : messages })

/views/partials/session_flash.jade:

/views/partials/session_flash.jade:

div.alert.alert-error
  each message in messages
    =message

/controllers/index.js

/controllers/index.js

req.assert(['user', 'username'], 'Please enter a valid username').len(3, 23);
req.assert(['user', 'email'], 'Please enter a valid email').isEmail();
req.assert(['user', 'password'], 'Please enter a valid password').len(3, 23);
req.session.messages = 'Please fix the errors below';
    errors = req.validationErrors();

    if (errors) {
      console.log(errors);
      res.render('join', {
        title : 'Join -',
        errors: errors,
        params: params
      });
      return;
    }

是否仅在刷新后(在POST之后)显示它,因为我是从/controllers/index.js而不是/app.js内部渲染联接模板的?另外,我应该在配置中执行类似delete req.session.messages的操作吗?我在任何地方都找不到完整的示例,而我发现的示例已经过时了.

Is it only showing up after I refresh (after a POST) because I'm rendering the join template from within /controllers/index.js and not /app.js? Also, should I be doing something like delete req.session.messages within my configuration? I couldn't find a complete example of this anywhere and the ones I've found were outdated.

推荐答案

看起来您确实在使用一个过时的示例. Express v3.x不再使用局部函数.请参阅Wiki中的查看系统更改 .而是使用

Looks like you are indeed using an outdated example. Express v3.x doesn't use partials anymore. See View system changes in the wiki. Instead use blocks and includes.

在登录时显示错误消息的简单方法是

An easy way to show error messages on login would be

index.js

app.locals.error = null;

app.post('/login', function(req, res){

  var name = req.body.name;
  var password = req.body.password;

  if (!name || !password) {
    res.status(400);
    return res.render('login', {
      error: 'All fields are required'
    });
  }

})

app.locals.error = null将错误的默认值设置为null.这样一来,您不必在每次渲染login.jade时都设置error变量,并且不存在error.

app.locals.error = null sets the default value of the error to null. By doing that you don't have to set the error variable every time you render login.jade and no error is present.

res.render('login', {
  error: null
});

您的login.jade模板可能看起来像这样

Your login.jade template could look like this

extends layout

block content
  - if (error)
    p= error
  form(method='post', action='/login')
    p
      label(for='name') Username:
      input(type='text', name='name', id='name')
    p
      label(for='password') Password:
      input(type='password', name='password', id='password')
    p
      input(type='submit', value='Submit')

这篇关于会话Flash消息仅在单独刷新后显示,而在Express中不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆