hapijs如何在每个请求中检查会话

时间:2019-06-14 12:08:37

标签: session-cookies hapijs

我想知道在每次调用hapijs服务时检查h.state的最佳方法是什么。

我这样创建会话:

server.route({
    method: 'POST',
    path: '/createSession',
    config: {
        cors: {
            origin: ['mysite']


        }
    },
    handler: function (request, h) {
        let cookie = request.state.session

        if (!cookie) {
            cookie = {
                username: 'emiliano',
                firstVisit: false                   
            }
        }
        cookie.lastVisit = Date.now()
        return h.response('test').state('session', cookie)
    }

});

如何检查每个请求中是否存在cookie?  可以在server.ext中做到这一点吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Hapi的生命周期方法并创建一个简单的插件来检查每个请求中的cookie。您可以使用onPreHandler,因为hapi会在路由处理程序之前和内部cookie(状态)之后执行onPreHandler。如果您想在其他一切之前(在cookie解析之前)进行干预,则可以使用onRequest

这是您可以使用的简单插件。您还可以阅读有关生命周期方法here

的更多信息
exports.plugin = {
    async register(server, options) {
        server.ext('onPreHandler', async (request, h) => {
            // do your cookie stuff here

            return h.continue;
        });      
    },
    name: 'check-cookie'    
};