首页 > 解决方案 > HapiJS:根据request中传入的查询参数配置HapiJs API?

问题描述

我的 API 是用 Hapijs 编写的。并希望基于对象配置 API queryParamsrequest我有一个带有端点的 API,/test并且queryParamstype=atype=b。如果type等于'a',那么我需要传入falseauth如果type等于,'b'那么我需要传入true.auth

   {
        method: 'GET',
        path: '/media',
        handler: function (request, reply) {
            TestModule.getTestData(request.query).then(reply,(err) => {
                reply(err);
            });
        },
        config: {
            description: 'This is the test API',
            notes: 'Returns a message',
            tags: ['api', 'Test'],
            auth: false // Here I need to do something.
        },
    }

你能告诉我我能做什么吗?

我正在这样做:

   {
        method: 'GET',
        path: '/media',
        handler: function (request, reply) {
            TestModule.getTestData(request.query).then(reply,(err) => {
                reply(err);
            });
        },
        config: {
            description: 'This is the test API',
            notes: 'Returns a message',
            tags: ['api', 'Test'],
            auth: request.query.type==='a'?false:true // Here I need to do something.
        },
    }

但得到一个错误ReferenceError: request is not defined

标签: node.jshapijs

解决方案


我不认为你能做到这一点。

为什么不只评估 response.query.type 然后根据类型重定向?

 {
    method: 'GET',
    path: '/media',
    handler: function (request, reply) {

        const {
         type
        } = request.query;

        TestModule.getTestData(type).then(reply,(err) => {
            if(type === a) {
             // do something
            }
            //do something else
            reply(err);
        });
    },
    config: {
        description: 'This is the test API',
        notes: 'Returns a message',
        tags: ['api', 'Test'],
        auth: false // Here I need to do something.
    },
}

推荐阅读