我的API是用Hapijs编写的。并希望基于queryParams的request对象配置API。我有一个带有端点/test的API,queryParams是type=a或type=b。如果type等于'a',那么需要在auth中传递false,如果type等于'b',则需要在auth中传递true。
{
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。
发布于 2019-07-26 15:30:01
我不认为你能做到。
为什么不只是计算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.
},
}发布于 2019-07-26 19:06:29
您可能需要一个可选/尝试auth策略模式。详情请参见https://hapijs.com/api/#-routeoptionsauthmode。最终结果是
{
method: 'GET',
path: '/media',
handler: function (request, reply) {
if (request.query.type !== 'a' && !request.auth.isAuthenticated) {
return reply(Boom.unauthorized('GET /media not allowed'));
}
TestModule.getTestData(request.query).then(reply,(err) => {
reply(err);
});
},
config: {
description: 'This is the test API',
notes: 'Returns a message',
tags: ['api', 'Test'],
auth: {
strategy: 'your auth strategy',
mode: 'try' // depending on your strategy. If you use a already existing strategy you probably want to use try as it will authenticate what it can and then you can still decide what to do in your handler.
}
}
}https://stackoverflow.com/questions/57218669
复制相似问题