如何在Hapi JS中设置Flash消息?
好吧,我尝试使用hapi-flash,但是它对我没有用.因此,这里的任何人都在Hapi JS中使用Flash消息
Well, i tried to use the hapi-flash but it didnt work for me. So any one here using flash messages in Hapi JS
是的,您需要使用 Yar .将其注册为插件后,可以在每个处理程序中使用:
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.');
要获取Flash消息,请使用request.session.flash('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.
我发现onPreResponse扩展对我们很有帮助,以获取所有Flash消息并将它们默认添加到上下文中.如果结束此操作,请确保在注册yar之前先注册扩展点.
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.
假设您的api/网站已在服务器上注册为插件:
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();
};
处理程序将如下所示:
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
};