Autoplay

    hapi.js - Up and running

    Mike FreyMike Frey

    hapi is a rock solid server framework for Node.js. Its focus on modularity and configuration-over-convention makes it the perfect match for any size development team. This video will introduce you to hapi by showing you the bare minimum needed to run a hapi server.

    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 The first thing we need to do is install Hapi. We'll do "npm install hapi --save," which will save it to the package.json file as a dependency. Next, I'll use nodemon to watch for changes to files in my project directory. Nodemon will automatically restart the server any time it detects a changed file.

    00:26 In my index.js file, I need to pull in the Hapi framework by requiring it and assign it to the variable "hapi." Next, I'll create a new instance of the Hapi server class, then add a connection which tells the server which host and port to listen on.

    00:48 To add a basic route, I'll use the server's route method and pass in a configuration object that tells the route how to behave. Every route configuration needs three things, a method that tells the router which HTTP verb or verbs to watch for, a path string for the URL to match, and a handler function to handle a request.

    01:07 The handler function takes two arguments, "request" and "reply." I'll just use "reply" to respond with a string of "Hello Hapi."

    01:18 The last thing we need to do is tell the server to start. Server.start takes a callback function, letting us know that the server has been started. I'll log the connection's URI here. Now, when I refresh the browser, it responds with the string "Hello Hapi."

    Discuss

    Discuss