Exercise 1: Building a Basic Hapi.js Server

In this exercise, we're going to build a basic HTTP server like the one before, but now with Hapi.js. You will notice how most of the things are done for us under the hood with Hapi.js. However, Hapi.js is also built on top of the http module.

For the rest of the exercises, from the first exercise of Chapter 3, Building the API â€“ Part 2, we will be building on top of each exercise as we progress. So, we might need to go back and modify previous files and so forth:

  1. In your Lesson-2 folder, create a subfolder called hello-hapi.

Use the exercise-b1 folder for your reference at Code/Lesson-2.
  1. On the Terminal, change directory to the root of the hello-hapi folder.
  2. Initialize it as a basic Node.js project and run the following command:
npm init -y
  1. Create a file, server.js.
  2. Install Hapi.js by executing the following command:
npm install hapi --save
  1. In the file, write the following code:
const Hapi = require('hapi');
// create a server with a host and port
const server = new Hapi.Server();
server.connection
({
host: 'localhost',
port: 8000,
});
// Start the server
server.start((err) =>
{
if (err) throw err;
console.log(`Server running at: ${server.info.uri}`);
});

Use the server.js file for your reference at Code/Lesson-2/exercise-b1.

Let us try to understand the code:

  • We first start by requiring the Hapi.js framework that we just included.

Recall our subtopic, The Module System, in Chapter 1, Introduction to Node.js? We looked at third-party modules—this is one of them.
  • We then create a server by initializing the Server class, hence a new Hapi.Server().
  • We then bind that server on a specific host (localhost) and port (8000).
  • After that, we create an example route, /. As you can see, for each route created, we have to specify three major things (as keys of an object passed to the server.route method):
    • method: This is the HTTP method for that route. We're going to look more deeply at the types of HTTP verbs in a later section. For our example, we're using GET. Basically, as the name suggests, this gets stuff/resources from the server.
    • path: This is the path on the server to the particular resource we are getting.
    • handler: This is a closure (anonymous function) that does the actual getting.

We're going to look at another extra key, called config, in our main project.
  • After this setup is done, we then start the server using the server.start method. This method accepts a closure (callback function) that is called once the server has started. In this function, we can check whether any errors occurred while starting the server.
  1. Run the server by going to the Terminal, and run the following command:
node server.js
  1. You should see this printed on the Terminal:
Server running at: http://localhost:8000

You should see something similar to this at http://localhost:8000:

Open another Terminal, change directory to the same project folder, and run the same command, node server.js. We'll get this error: Error: listen EADDRINUSE 127.0.0.1:8000.

The reason we get this error is because we can only have one server running on a particular port of our host. Remember that the host IP 127.0.0.1 is what we refer to as localhostif (err) throw err; is the line which throws the error.

We can fix this by changing the port number of our second server to something like 8001. However, as best practice, other than keep changing the code, we can pass the port number as a Terminal argument, that is, running the app as, node server.js <port-number>, then changing our code (in the port section) to, port: process.argv[2] || 8000,.

Here, we're saying, if the port is provided as the first argument of the script, use that, otherwise, use 8000 as the port number. Now, when you run: node server.js 8002, the server should run okay from localhost:8002.

For the process.argv array, index 0 is the program running the script, node and index 1 is the script being run, server.js. Arguments passed to the script are therefore counted from index 2 onwards. You can read more about process.argv here later on.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset