This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

hapi.js - Replying to Requests

1:52 Node.js lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

Avatar
PPSong

Hi,

First of all, thanks for the lesson
I'd like to know what tool/module/package do you use for this command: 'http GET localhost:8000'?

Looking forward to your reply, thanks!

Avatar
Mike

I'm using a python util called httpie.

In reply to PPSong

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.

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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?