LoginSignup
3
3

More than 5 years have passed since last update.

NodeJSフレームワーク hapiを触ってみる

Posted at

hapiフレームワークについて調べたことまとめ

モチベーション

  • NodeJSで何かしらコードを書きたい
  • 簡単な記述で書きたい(細かい設定等気にしたくない

hapiを選択した理由

コーディングがjson形式で書ける部分があり、とっつきやすいと思った(主観

hapiのインストール

hapi v17.0.0をインストール(2018年2月時点で最新)
nodeJSのバージョンv8.9.0以降が必要となります。

npm install --save hapi@17.0.0

日本語のhapiの記事を探すと2015年くらいのものばかり出てきて
hapi v10くらいの頃の記事がヒットしてきて、そのまま書いても
動かないものばかり...
それくらい成長しているとポジティブに捉えてこのまま進めていきます。

hapiのサンプルコードの実行

公式サイト(https://hapijs.com)のGetting Startedを元に進めます。
下記のようなサンプルコードを作成します。
やっていることは

  • hapiモジュールの呼び出し
  • serverのIP(localhost),ポート(8000)の指定
  • ルーティングの指定
    • HTTPのリクエストメソッドの指定(GET,PUT,POST,DELETE等)
    • パスの指定(localhost:8000/helloで呼び出せる
    • 呼び出し時のハンドラ(関数)の指定
  • サーバの実行
servers.js
'use strict';

const Hapi = require('hapi');

// Create a server with a host and port
const server = Hapi.server({ 
    host: 'localhost', 
    port: 8000 
});

// Add the route
server.route({
    method: 'GET',
    path:'/hello', 
    handler: function (request, h) {

        return 'hello world';
    }
});

// Start the server
async function start() {

    try {
        await server.start();
    }
    catch (err) {
        console.log(err);
        process.exit(1);
    }

    console.log('Server running at:', server.info.uri);
};

start();

下記コマンドでサーバを立ち上げます。

node server.js

localhost:8000/helloにアクセスしてみると
hello worldと表示されます。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3