Démarrer avec hapijs

Bonjour le monde

Créez un fichier server.js avec le contenu suivant :


'use strict';

const Hapi = require('hapi');

// Create a server instance
const server = new Hapi.Server();

// Specify connections (server available on http://localhost:8000)
server.connection({ 
    port: 8000 
});

// Add a route
server.route({
    method: 'GET',
    path:'/hello', 
    handler: function (request, reply) {
        return reply('hello world');
    }
});

// Start the server
server.start((err) => {
    if (err) {
        throw err;
    }

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

Démarrer le serveur Hapi.js

Exécutez node server.js et ouvrez http://localhost:8000/hello dans votre navigateur.

Passer des paramètres à une route

Les paramètres peuvent être spécifiés dans la propriété path de la configuration de la route

'use strict';

const Hapi = require('hapi');

// Create a server with a host and port
const server = new Hapi.Server();

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

// Add a route path with url param
server.route({
    method: 'GET',
    path:'/hello/{name}', 
    handler: function (request, reply) {
        // Passed parameter is accessible via "request.params" 
        return reply(`Hello ${request.params.name}`);
    }
});

// Start the server
server.start((err) => {
    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});

Validation

'use strict';

const Hapi = require('hapi');
const Joi = require('joi');

// Create a server with a host and port
const server = new Hapi.Server();

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

/**
 * Add a route path with url param
 */
server.route({
    method: 'GET',
    path:'/hello/{name}', 
    handler: function (request, reply) {
        // Passed parameter is accessible via "request.params" 
        return reply(`Hello ${request.params.name}`);
    },
    config: {
        // Validate the {name} url param
        validate: {
            params: Joi.string().required()
        }
    }
});

// Start the server
server.start((err) => {
    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});