2015-10-06 25 views

回答

3

是的,你會想要使用Yar。一旦你把它註冊爲一個插件,每個處理程序中,你可以使用:

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

爲了獲得閃光燈的消息,您使用request.session.flash(「錯誤」)。這將返回當前閃存中的所有'錯誤'消息。它也將清除閃回 - 具體可以在回購中找到。

我發現它有助於我們onPreResponse擴展來獲取所有的flash消息並默認將它們添加到上下文中。如果你這樣做結束,確保在註冊yar之前註冊擴展點。

假設你的API /網站註冊爲一個服務器上的插件:

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

謝謝。但將它使用hapi-auth-cookie作爲即時通訊使用本地護照 – tezlopchan

+0

它應該適用於任何設置。你只需要確保你通過request.session.flash('type','message')設置處理程序中的flash – jrmce