ppb
ppb

Reputation: 2643

Hapi-Swagger failing with header value

I am using hapi-swagger in our application where one of API trying to use custom header but when I ivoke that API with custom header getting below error

{
"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request headers input"
}

Below the API where I am using headers with validator.

{
        method: 'POST',
        path: '/v1/testapi',
        config: {
            description: 'Greet user',
            notes: ['Use to greet a user'],
            tags: ['api'],    
            handler: function ( request, h ) {
                console.log('sending response...');
                return h.response('OK');
            },
            validate: {
                headers: {
                    name: Joi.string().required()
                }
            }                               
        }
    }

Below are the versions we are using.

"hapi": "17.2.2",

"hapi-swagger": "9.1.1",

"joi": "13.1.2",

Upvotes: 1

Views: 1702

Answers (1)

Ryan
Ryan

Reputation: 106

I ran into this recently. You need to use the allowUnknown validation option to allow unknown headers (https://github.com/hapijs/hapi/issues/2407#issuecomment-74218465).

validate: {
    headers: Joi.object({
        name: Joi.string().required()
    }).options({ allowUnknown: true })
}

Also note that hapi 17 changed the default behavior for reporting validation errors. If you want to log or return the actual error indicating which headers are failing validation rather than a generic "Bad Request" you can add a custom failAction hander (https://github.com/hapijs/hapi/issues/3706).

Upvotes: 5

Related Questions