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 - POST and PUT request payloads

    Mike FreyMike Frey

    hapi makes handling POST and PUT payloads easy by buffering and parsing them automatically without requiring additional modules or middleware. This video will demonstrate how to handle JSON and form based request payloads via hapi's route configuration.

    hapihapi.js
    nodeNode.js
    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:00 I have a very simple hapi service set up to run on port 8000, and I've already started it with nodemon. To handle request payloads we need to have a route set up that handles POSTs or PUTs. I'll just add a route and then set a method on an array containing both POST and PUT. For this demonstration, the path can stay as is, and I'll just have the handler echo the request payload. The request payload is where hapi places the content of the request body.

    00:25 Now we'll use HTTPI to make a POST request from my terminal. I'll add fname and lname properties to the request that HTTPI will automatically turn into a JSON payload. The first JSON objects is the request body, and the second is the response body, and they match. If I change the request from a POST to a PUT, the data is handled the same way. If I add the --form option to HTTPI you can see that the request body was URL encoded and the response was output as JSON.

    01:01 Hapi loads the request body into memory and parses it by default for any request that is not a GET or HEAD request, and it will detect and parse a number of different payload MIME types, like JSON and URL encoded forms. If I were to configure the route for the default payload behavior, I'd add a config section to the route containing a payload object. The output property determines how the payload is represented, the default is data. The parse property determines if the payload is processed or presented raw, the default is true.

    01:34 Running the form PUT again shows that the route is behaving the same as before. If I set the parse option to false and make the form PUT request again, the request and the response match because hapi did not parse the URL encoded string into a JSON object. If I decide that I only want support JSON payloads, I would add an allow property and lock it to application/JSON. Now form PUT request results in an unsupported media type error.

    Discuss

    Discuss