[Hapi.js] Extending the request with lifecycle events

Instead of using middlware, hapi provides a number of points during the lifecycle of a request that you can hook-in to provide additional functionality, called "extension events". This lesson will give you an introduction to using extension events, and show how they can be used to manipulate the request or response in-flight.

const Hapi = require( ‘hapi‘ )
const Boom = require( ‘boom‘ )
const server = new Hapi.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 has 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 has 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 is validated on pre-response runs, and the response is 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 are these extensions good for? Each extension can be used to manipulate the request or response at any point in the lifecycle. For example, in onRequest, I can force all requests to be interpreted as GETs to the route path.

To do so, I‘ll use request.seturl, pass in the string/, and pass the string GET to request.setmethod. Now, when I make a post request to /foo, it still hits my defined route.

时间: 2024-08-03 15:04:09

[Hapi.js] Extending the request with lifecycle events的相关文章

[Hapi.js] Friendly error pages with extension events

hapi automatically responds with JSON for any error passed to a route's reply()method. But what if your application needs errors rendered in HTML? This lesson shows how to implement friendly HTML error messages using hapi extension events. const Hapi

[Hapi.js] Request Validation with Joi

hapi supports request validation out of the box using the joi module. Request path parameters, payloads, and querystring parameters can be validated with joi's simple, 'use strict' const Hapi = require('hapi') const Joi = require('joi') const server

[Hapi.js] View engines

View engines, or template engines, allow you to maintain a clean separation between your presentation layer and the rest of your application. This post will demonstrate how to use the vision plugin with hapi to enable template support. index.js serve

[Hapi.js] Logging with good and good-console

hapi doesn't ship with logging support baked in. Luckily, hapi's rich plugin ecosystem includes everything needed to configure logging for your application. This post will introduce good, a process monitor for hapi, and good-console, a reporter for g

[Hapi.js] Managing State with Cookies

hapi has built-in support for parsing cookies from a request headers, and writing cookies to a response, making state management easy and straight-forward. It even has built in support for cookie encryption and auto detects when a cookie contains JSO

[Hapi.js] Route parameters

Routing is a fundamental aspect of any framework. In this lesson, you'll learn how to use path parameters in hapi's router. We'll also touch on how the router uses specificity to order routes internally. Router Param: http://localhost:8000/ztw // Wil

[Hapi.js] Replying to Requests

hapi's reply interface is one of it's most powerful features. It's smart enough to detect and serialize objects, buffers, promises and even streams. This post will demonstrate first hand how to use the reply method to send your data to the client, no

[Hapi.js] Serving static files

hapi does not support serving static files out of the box. Instead it relies on a module called Inert. This lesson will cover serving static files using Inert's custom handlers. 'use strict' var Hapi = require( 'hapi' ); var Boom = require('boom'); v

[Hapi.js] Using the response object

When you use reply method: let resp = reply('hello world') It actually return an response object. By using response object, you can modiy the response's status code, header, cookie, type and so on... server.route({ method: 'GET', path: '/', handler: