hapi.js - Using the response object

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

Think of hapi's reply() function as "what you want to say" and the response object as "how you want to say it". While reply controls the payload sent to the client, the response object will allow you to control how the client interprets the payload by manipulating status code, content type, state and more.

[00:01] When a route's reply method is called with anything but an error, it returns a response object. This response object has a few properties like status code and headers, but in the context of a route handler, they are not very useful because the status and headers can't be changed by modifying the properties.

[00:17] Instead, response object provides a number of functions for mutating the response before it gets sent back to the client. Let's take a look at a few of them. HAPI defaults to the status code of 200 for a normal reply, but the code method lets you change the status code of the response. I'll change it to 418, then make a request, and you can see that it is set appropriately.

[00:37] HAPI also tries to detect the MIME type of a response by default, but sometimes it needs a little help. I'm sending plain text, but HAPI is defaulting it to a MIME type of text HTML. I can use the type method to change it to text plain, and now the content header reflects text plain.

[01:01] I can set other headers using the header method. The first argument is the header name, and the second is the value. I'll set the header hello with a value of world, and the header shows up when I make a request.

[01:16] I could set cookies with the header method, too, but there is a method called state that is specific to setting cookies. Like header, the first argument is the key, and the second is the value. I'll repeat the hello world theme once again, and the set cookie header shows up in the response.

[01:33] The last thing I want to mention is that the response object is chainable, so I can make this a bit more concise by removing the references to RESP, and the route responds the same way as before.