This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    hapi.js - Replying to Requests

    Mike FreyMike Frey

    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 video will demonstrate first hand how to use the reply method to send your data to the client, no matter the format.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:01 Hapi's route reply method is used to end a request and signal to the framework that a response should be sent to the client. When called without arguments, Hapi responds with a 200 and empty payload.

    00:12 In general, reply looks for two arguments following the idiomatic error-first pattern of node.js callbacks. However, Hapi does not require that the error is argument is used. Reply will inspect the first arguments type, only responding with an error if the first argument is in fact an error. Otherwise, it assumes that it should be the response payload.

    00:33 Hapi will also make assumptions about how to respond to the client based on other types passed to reply. When replying with an object, Hapi changes the content type header to application JSON and stringifies the object. If a promise is passed into reply, Hapi will wait for the promise to resolve or reject, then serve the result or error.

    01:01 Reply can also handle streams. I'll create a read stream for the current file, and Hapi will handle piping it to the response stream and all the cleanup. Now the content of my index file is returned to the client. If I pass an error object to reply, Hapi will respond to the client with a 500 error.

    01:26 Responding that way from an error isn't always ideal. Internally, Hapi wraps the error in a Boom object. We can use Boom to respond with a different error type. I'll require in Boom, then pass Boom.notfound into reply. Now the request responds with 404 not found instead of a 500.

    Discuss

    Discuss