node.js: Rest API (calculator)

mkdir calculator
cd calculator
npm init
npm install — save hapi
touch index.js
//Framework hapi.jsconst Hapi = require('hapi');// Machine and logical portconst host = 'localhost';const port = 8000;// Create the serverconst server = Hapi.Server({host: host,port: port});// Start the serverconst init = async () => {await server.start();console.log("Server up no porto: " + port);}// App launchinit();
node index.js
The result, at this moment
server.route ({
method: 'GET',
path: '/ calculator / about',
handler: function (request, h) {

var data = {
msg: 'Calculator API'
};

return data;
}
});
http://localhost:8000/calculator/about

App organization (MVC)

mkdir routes
cd routes
touch routes.js
// Define routersrequire('./routes/routes')(server);
module.exports = function(server) {
//route Somaserver.route({method: 'GET',path: '/calculator/soma/{num1}/{num2}',handler: function (pedido) {const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 + num2};return data;}});//route Subtraçãoserver.route({method: 'GET',path: '/calculator/sub/{num1}/{num2}',handler: function (pedido){const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 - num2};return data;}});
//route Multiplicaçãoserver.route({method: 'GET',path: '/calculator/multi/{num1}/{num2}',handler: function (pedido){const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 * num2};return data;}});//route Divisãoserver.route({method: 'GET',path: '/calculator/div/{num1}/{num2}',handler: function (pedido){const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 / num2};return data;}});
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Afonso Antunes

Afonso Antunes

Finalist student in Computer Engineering