30
loading...
This website collects cookies to deliver better user experience
someproject
on your machine so that it contains the necessary files.Ctrl + Alt + T
) and run the following command. Running the command will create a new folder someproject
in the current directory and change the current directory to someproject
directory.$ mkdir someproject && cd someproject
npm init
. If you run this command, you will be asked some information. We can keep the default information. If you want, you can change it from the package.json.$ npm init -y # Generate it without having it ask any questions
$ npm install @hapi/hapi -S # saving hapi as a dependency by adding -S to npm i
Hapi.Server()
. After that, you have to say host
and port
as server options of the server.// server.js
const Hapi = require('@hapi/hapi');
(async () => {
// start your server
try {
// create a server with a host and port
const server = new Hapi.Server({
host: 'localhost',
port: 3000
});
await server.start();
console.log('Server running at: ', server.info.uri);
}catch (err) {
console.error(err);
}
})(); // IIFE
# file stracture
|-- node_modules
|-- package.json
|-- server.js
"Hello World"
as a response.server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
server.js
file, the code will look like the following code.// server.js
const Hapi = require('@hapi/hapi');
(async () => {
// start your server
try {
// create a server with a host and port
const server = new Hapi.Server({
host: 'localhost',
port: 3000
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
// business logic
return 'Hello World!';
}
});
await server.start();
console.log('Server running at: ', server.info.uri);
}catch (err) {
console.error(err);
}
})(); // IIFE
server.js
file, if you request to localhost:3000
, the response will be Hello World!
.['GET', 'POST']
). Define the path property and request the endpoint URL of this route. And you have to write the main business logic of your route in this handler. The handler must return someting, otherwise it will give an error.$ node server.js