Lesson 2: Working with web services CHAPTER 8 367
In this example, a math_service folder is created under the node_samples folder, and the
following package.json file is created.
{
"name": "math_service",
"version": "0.0.0",
"description": "A simple Web service",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": "",
"author": "Glenn Johnson",
"license": "BSD",
"private": true,
"dependencies": {
"formidable": "1.x",
"express": "3.0.0",
"math_example": "0.x"
}
}
In this example, there are three dependencies. After you create this file and save it, you
can open a command prompt window, navigate to the math_service folder, and execute the
following command to install the dependencies from npm.
npm install
After the installation completes, you can use these packages. In the math_service folder,
create an app.js file and add references to these packages as follows.
var express = require('express');
var app = express();
var formidable = require('formidable');
var math = require('math_example');
After setting up the package references, create a public folder under the math_service
folder and use the app object to mount the public folder as the root of the website. The pub-
lic folder will house webpages. The code should look like the following.
app.use(express.static(__dirname + '/public'));
In this example, the operations will be part of the URL, so the addition operation is created
by adding the following code.
app.get('/addition', function (request, response) {
var x = Number(request.query.x),
y = Number(request.query.y),
result = math.addition(x, y);
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end('{ "result": ' + result + '}');
console.log('Handled addition request for x=' + x + ' : y=' + y);
});