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