Instead of using Middlware, HAPI provides a number of points during the lifecycle of a request that you can hook-in to Pro Vide additional functionality, called "extension events". This lesson would give you a introduction to using extension events, and show how they can be used to manipulate the Reque St or response in-flight.
Const HAPI = require (' Hapi ') Const Boom= Require (' boom ')) const Server=Newhapi.server () server.connection ({port:8000}) Server.ext (' ONrequest ', (request, reply) ={Request.seturl (‘/‘) Request.setmethod (' GET ' ) //need to call continue, the same as Express ' s next ()Reply.Continue()} )/** * After the request have gone through the router, it needs to be authenticated. Onpreauth runs before authentication, and Onpostauth runs after. */Server.ext (' ONrequest ', (request, reply) ={Console.log (' ONrequest ') reply.Continue()} )/** * After the request have gone through the router, it needs to be authenticated. Onpreauth runs before authentication, and Onpostauth runs after. */Server.ext (' Onpreauth ', (request, reply) ={Console.log (' Onpreauth ') reply.Continue()}) Server.ext (' Onpostauth ', (request, reply) ={Console.log (' Onpostauth ') reply.Continue()} )/** * Validation is handled next. Onprehandler runs, then, the route itself. */Server.ext (' Onprehandler ', (request, reply) ={Console.log (' Onprehandler ') reply.Continue()} )/** * Onposthandler runs after the handler.*/Server.ext (' Onposthandler ', (request, reply) ={Console.log (' Onposthandler ') reply.Continue()} )/** Then, the response payload are validated on Pre-response runs, and the response are sent to the client.*/Server.ext (' Onpreresponse ', (request, reply) ={Console.log (' Onpreresponse ') reply.Continue()}) Server.route ({method:' GET ', Path:‘/‘, Handler:function(Request, Reply) {Console.log (' Handler ') Reply (' Hello World ')}}) Server.start (()= {} )
What is these extensions good for? Each extension can is used to manipulate the request or response at any of the lifecycle. For example, in ONrequest, I can force all requests to be interpreted as GETs to the route path.
To does so, I'll use Request.seturl, pass in the string/, and pass the string GET to Request.setmethod. Now, if I make a POST request To/foo, it still hits my defined route.
[Hapi.js] Extending the request with lifecycle events