In this blog, we will learn how to Adding routes in Hapi.
Steps.
– Define the path.
– Define the method.
– Define the handler.
let’s see an example of it
[cc lang=”javascript”]
var Hapi = require(‘hapi’);
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.route({
method: ‘GET’, // define the method
path: ‘/’, // define the path
handler: function (request, reply) { //define the handler
reply(‘Hello, world!’);
}
});
server.start(function () {
console.log(‘Server running at:’, server.info.uri);
});
[/cc]
– In 4th line, “server.route()“ method start. In this method we need to define method, path, and handler().
– In 5th line, we define the HTTP method (like, GET,POST) or you can use * which accepts all method.
– In 6th line, we define the path or you can say URL, the user must type the path in order view this route.
– In 7th line, we define “handler function()“ ,
– In this function, Hapi will pass in 2 objects
– first one is the request object.
– second one is the reply object.
– In 11th line we start the server using “server.start()“ method.