How to set Flash Messages in Hapi JS?

南笙酒味 提交于 2019-12-06 12:00:40

问题


Well, i tried to use the hapi-flash but it didnt work for me. So any one here using flash messages in Hapi JS


回答1:


Yes, you'll want to use Yar. Once you've registered it as a plugin, within each handler you can use:

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

To get the flash message, you use request.session.flash('error'). Which will return all the 'error' messages currently in the flash. It will also clear the flash - specifics can be found on the repo.

I find it helpful to us the onPreResponse extension to grab all of the flash messages and add them to the context by default. If you end of doing this, make sure to register the extension point before registering yar.

Assuming you're api/website is being registered as a plugin on a server:

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

And a handler would look something like this:

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


来源:https://stackoverflow.com/questions/32963596/how-to-set-flash-messages-in-hapi-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!