Framework Hapi | Create Server

Langkah

Pastikan sudah membaut projek dan mengunduh modul @hapi/hapi. Pertama buat file index.js, file ini digunakan untuk server

        
// Membuat file
$ touch index.js
        
      
Kemudian untuk kode server dari hapi
        
const Hapi = require('@hapi/hapi');

const init = async() => {
  // Untuk konfigurasi server
  const server = Hapi.server({
    port: 3000,
    host: 'localhost'
  });

  // Untuk route, deklarasi untuk alamat yang akan diakses
  server.route({
    method: 'GET',
    path: '/hello',
    handler: function(request) {
      return `

Hello from server

`; } }); // Karena async maka perlu await hingga server berhasil dijalankan await server.start(); console.log('Server running on %s', server.info.uri); }; // Untuk handle eror process.on('unhandledRejection', (err) => { console.log(err) process.exit(1); }); // Panggil fungsi init();
Jika sudah dapat diakses lewat browser atau curl dengan method GET dan alamat http://localhost:3000/hello, maka akan terdapat tulisan "Hello from server".
        
$ curl -X GET http://localhost:3000/hello -i
HTTP/1.1 201 Found
content-type: text/html; charset=utf-8
cache-control: no-cache
content-length: 26
Date: Tue, 18 Mar 2025 02:19:37 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Hello from server