Getting Started with Hapi.js

in #programming6 years ago

hapijs-1024x528.jpg
In this article, you will be familiar with a rich framework for building applications and services and it’s Hapi.js. Hapi enables developers to focus on writing reusable application logic instead of spending time building infrastructure.

Now I write this article the current version of Hapi is 17.7.0 and in this article, I will briefly explain it very quickly and after that, I will teach you how to create the first project I in Hapi.js.

What is Hapi.js?
Hapi (pronounced “happy”) is a web framework for building web applications, APIs and services. It’s extremely simple to get started with an extremely powerful at the same time. The problem arises when you have to write performant, maintainable code.

Who is using hapi.js?

Screen-Shot-1397-08-18-at-10.40.54-PM.png

You can see the Hapi community here.

What can you do with Hapi?

1- You can use Hapi as an API Server

hapi has simplified the way in which you can write highly scalable APIs. It is powerful and features a rich framework with a robust architecture. Here is the architecture of the Hapi API server:

2- You can use Hapi as a Website Server

You can also build a website server application with Hapi. Your client or browser will send the request for index.html to Hapi, which will have a templating engine like EJS or Jade. These templating engines render the dynamic content in HTML. After finishing rendering in HTML, Hapi will send the index.html to the browser.

3- You can Hapi as an HTTP Proxy

Another use for Hapi is as an HTTP proxy. Walmart uses Hapi as a proxy HTTP service; while the majority of the business service is still served from the Java external service, all the incoming traffic is sent through a proxy server.

Recommended Tools

Which tools am I using throughout this article?

The first tool is Visual Studio Code (VSC). You can download it for free right here on code.visualstudio.com and here is the link.

Of course, you can use any code editor, text editor or IDE of your choice. I just use Visual Studio Code because we think it’s really nice to use, really powerful and for this reason a good choice for this article.

Create the first project with Hapi

I know what Hapi actually is and I want to have a fun practice with it. For that, I’m going to Install Hapi.

First of all, you should install Node on your computer and for that, you can visit nodejs.org and download and install it.

After installing Node, Open the Terminal on Linux or Mac OS or command prompt if you are using windows and Create a new directory,mkdir myproject and from there.

Run: cd myproject this goes into the created project folder.
Run: npm init and follow the prompts, this will generate a package.json file for you.
Run: npm install --save hapi@17.x.x this installs Hapi and saves it in your package.json as a dependency of your project.
Now you should create a server by creating a new instance of hap.Server(), So create a file and name it server.js, after that open file with VSC and write following code in it:

'use strict';

const Hapi = require('hapi');

const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

const init = async () => {

    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();

Now You create a server and you can add one or two routes so that it actually does something. Let’s see what that looks like:

'use strict';

const Hapi = require('hapi');

const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

server.route({
    method: 'GET',
    path: '/',
    handler: (request, h) => {

        return 'Hello, world!';
    }
});

server.route({
    method: 'GET',
    path: '/{name}',
    handler: (request, h) => {

        return 'Hello, ' + encodeURIComponent(request.params.name) + '!';
    }
});

const init = async () => {

    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();

Save the above as server.js and start the server with the command.node server.js Now you’ll find that if you visit http://localhost:3000 in your browser, you’ll see the text,Hello, world! and if you visit http://localhost:3000/stimpy you’ll see Hello, stimpy!.

The method parameter can be any valid HTTP method, array of HTTP methods, or an asterisk to allow any method. The path parameter defines the path including parameters. It can contain optional parameters, numbered parameters, and even wildcards.

And that’s it! It’s very easy and sweet!

Conclusion

I guess that got your feet wet, and you are excited to try out this exciting framework. In the upcoming tutorials, we’ll have a look at all the goodies in the request object; try out different request verbs, and use Paw to test our URLs.

If you get stuck, be sure to check the API documentation; they have some really good explanations there.

Follow Me to get more training on programming & Javascript @alihesari

Sort:  

Hello! Your post has been resteemed and upvoted by @ilovecoding because we love coding! Keep up good work! Consider upvoting this comment to support the @ilovecoding and increase your future rewards! ^_^ Steem On!

Reply !stop to disable the comment. Thanks!

Congratulations @alihesari! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!