如何在Hapi JS中设置Flash消息?

时间:2015-10-06 06:56:39

标签: node.js hapijs

好吧,我尝试使用hapi-flash但它对我没用。所以这里任何一个人都在Hapi JS中使用flash消息

1 个答案:

答案 0 :(得分:3)

是的,您需要使用Yar。一旦您将其注册为插件,您可以在每个处理程序中使用:

request.session.flash('error', 'There was an error.');

要获取flash消息,请使用request.session.flash('error')。这将返回当前闪存中的所有“错误”消息。它还将清除闪光灯的细节可以在回购中找到。

我发现onPreResponse扩展有助于获取所有flash消息并默认将它们添加到上下文中。如果您这样做,请确保在注册yar之前注册扩展点。

假设您将api / website注册为服务器上的插件:

exports.register = function (server, options, next) {
  server.ext('onPreResponse', internals.onPreResponse);
  server.register([
    {
      register: require('yar'),
      options: {
        cookieOptions: {
          password: process.env.SECRET_KEY
        }
      }
    }
  ], function (err) {
    Hoek.assert(!err, 'Failed loading plugin: ' + err);
    next()
};

internals.onPreResponse = function (request, reply) {

  var response = request.response;

  if (response.variety === 'view') {
    if (!response.source.context) {
      response.source.context = {};
    }

    // This can be slimmed down, but showing it to be explicit
    var context = response.source.context;
    var info = request.session.flash('alert');
    var error = request.session.flash('error');
    var notice = request.session.flash('notice');
    var success = request.session.flash('success');

    context.flash = {};

    if (info.length) {
      context.flash.info = info;
    }

    if (error.length) {
      context.flash.error = error;
    }

    if (notice.length) {
      context.flash.notice = notice;
    }

    if (success.length) {
      context.flash.success = success;
    }

    return reply.continue();
  }

  return reply.continue();
};

处理程序看起来像这样:

exports.login = {
  handler: function (request, reply) {
    // Do login stuff here

    request.log(['error', 'login'], err);
    request.session.flash('error', 'There was an error logging in. Try again.');
    return reply.redirect('/');
  },
  auth: false
};