WEB SERVICES - A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014

A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014)

CHAPTER 8: WEB SERVICES

All the chapters discussed till now dealt with browser level coding and scripting. However, now it is time to move on to server side scripting. This chapter focuses on the use of JavaScript at the server level, which is possible with the help of Node.js, and how you can work around with web services.

Basics of Node.js

Node.js is a platform, which is made on Google Chrome, and can be used for creating scalable and flexible applications. It allows you to write JavaScript code for the server. However, before you can begin, you must download and install Node.js on your system.

Writing a Basic Code

The first step is to open any text editor and create a file named myFile.js. In the file, write the code:

var http = require('http');

http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello World!\n');

console.log('Handled request');

}).listen(8080, 'localhost');

console.log('Server running at http://localhost:8080/');

The first line loads the http module while the second line creates a server object. The function createServer takes in two parameters, request and response. All the website handling is done from these functions. In this example, the response function ends by writing ‘Hello World’ on the screen.

The function createServer, returns a server object, which call the function, listen. This function listens at the port 8080 and the IP address of the host is set to 127.0.0.1. therefore, if there is a network adapter installed on your system, your web server will start listening to web requests rights away. The last line prints a line on the screen to let the user know that the server is running and listening to requests.

Once you have created the file and saved the contents of the file as mentioned above, you must open the command prompt and write the command:

Node myFile.js

Now, keeping the command prompt active, you must open the web browser and type the address: http://localhost:8080/

As soon as the request is sent and a response is received, the same is communicated to the user using the console window. If you have been able to do this successfully, then you have just created your first node.js website. If you wish to stop the running of the code, you can just press Ctrl+C.

Now that you know how requests are received, it is time to look at how these requests are processed and responses are generated. You may need to use the url module for parsing the QueryString.

The code mentioned below shows how you can parse the URL string and generate a response in accordance with it.

var http = require('http');

var url = require('url');

http.createServer(function (request, response) {

var url_parts = url.parse(request.url, true);

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hey ' + url_parts.query.name + '.\n');

console.log('Handled request from ' + url_parts.query.name);

}).listen(8080, 'localhost');

console.log('Server is running at: http://localhost:8080/');

You can test the running of this code in the similar manner as the previous code.

How to Create Node.js Module

You can create modules by writing code in the form of functions and then, calling these modules from the main code.

var myHttp = require('http');

var myUrl = require('url');

function start(){

http.createServer(function (request, response) {

var url_parts = url.parse(request.url, true);

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello ' + url_parts.query.name + '!\n');

console.log('Handled request from ' + url_parts.query.name);

}).listen(8080, 'localhost');

console.log('Server running at http://localhost:8080/');

}

exports.start = start;

when you save this piece of code in a file, a module is created. This module can be used by other functions using the require function. For instance, if the file is saved as sample1.js, then the start() can be used in another function using:

var samplex = require('./sample1.js');

sample1.start();

How to Create a Node.js package

A collection of modules is referred to as an application. Once you have published your package, it can be installed and used. Consider for example, a package of different mathematical modules.

The root folder must have the following:

README.md

\packName

\lib

main.js

\bin

mod1.js

mod2.js

Creating Aggregate Module

You may wish to make only one object for the user to access. The user should be able to access all the modules of the package through this object. In order to accomplish this, a main.js module must be created in the bin folder that must define the modules to be included in the module.exports.

How to Create README.md File

The README.md file is a help file that can be used by the developer as a startup guide for using your package. The extension of this file is .md, which is a short form for mark-down. This format gives readability to the text written in this file.

A sample file of this type is given below:

samplePackage package

====================

In samplePackage, the following functions are available:

- **add** Performs addition of two numbers and presents the result.

- **sub** Performs subtraction of one number from the other and presents the result.

How to Create package.json File

This file contains the metadata for the package and can be created manually using the command:

npm init

This command creates the file, which can later be edited. A sample file is given below:

{

"name": "sampleFile",

"version": "0.0.0",

"description": "This is a sample file ",

"main": "bin/main.js",

"scripts": {

"test": "echo \"This is a test file\" && exit 1"

},

"repository": "",

"keywords": [

"sample",

"example",

"add",

"sub"

],

"author": "XYZ",

"license": "ABC"

}

In addition to test scripts, you can also give git scripts, which are the best available source control managers.

How to Publish a Package

As mentioned previously, a package can be defined in terms of a folder structure. When you publish your package, you make it accessible to all users. In order to perform this operation, you must use the npm command, which is also the command used for searching and installing packages. However, you shall be required to create an account for yourself before publishing any of your packages using the command: npm adduser. After you enter the required information, your account is created. However, what this also means us that there is no validation required. Therefore, anyone can add code to the repository. Therefore, you should be careful while downloading and installing packages from the registry.

In order to publish a package, you simply need to go to the root directory of the package and enter the command npm publish in the command prompt.

How to Install and Use the Package

A package that is published can be downloaded and installed by any user. You simply need to go to the folder and give the command, npm install samplePackage. This installs the package locally. On the other hand, if you wish to install the package globally, you can give the command, npm install –g samplePackage. For a global installation, you will need to create a link from each application to the global install using the command, npm link samplePackage.

The route to a global install is a junction. You can get into the node_modules folder and back using the cd command. Once you are inside the folder, you can give the command: npm install contoso, to initiate an install. You can now write some code that uses the package. A sample is given below:

var samplePackage = require(‘samplePackage’);

var finalResult = 0;

console.log();

finalResult = samplePackage.add (5,10);

console.log('add (5,10) = ' + finalResult);

console.log();

result = samplePackage.sub (50,10);

console.log('sub(50,10) = ' + finalResult);

console.log();

console.log('done');

This code tests the modules of the package. You can execute the code using:

node main

The package can be uninstalled locally using:

npm uninstall samplePackage

However, if you wish to uninstall the package globally, you can do it using

npm uninstall -g samplePackage

How to Use Express

1. The first step is to install Node.js and create a sample for keeping all .js files and projects. Besides this, you must also install Express, which is a web application framework for Node.js development.

2. You can create a package using the following set of commands and instructions.

1. npm init

2. You can create myPackage.js file containing the following contents:

{

"name": "Sample",

"version": "0.0.0",

"description": "This is a sample website.",

"main": "main.js",

"scripts": {

"test": "echo \"Error: Test not specified\" && exit 1"

},

"repository": "",

"author": "XYZ",

"license": "BSD"

}

“private”: true,

“dependencies”: {

“express”: “3.0.0”

}

}

In order to use the file in Express, dependencies have to be added. Moreover, if you do not define it to be private, you may get an error from the firewall of your computer as it tries to load the page.

3. Give the install command: npm install

4. You can use the command, npm ls, to see if the package is present in the registry.

4. You can create a simple application using the following set of instructions:

3. Create a file myApp.js and add the following to the file:

var express = require('express');

var app = express();

2. You can define the route using the myApp.Method() syntax.

app.get('/', function(request, response){

response.send('Hey World!');

});

The code mentioned above will send the response ‘Hey World!’ as and when a request is received.

3. The last section of code that must be added is for listening to the request. This code is as follows:

var port = 8080;

app.listen(port);

console.log('Listening on port: ' + port);

4. Once the file is complete, you can save it and run it using the command, node app. So, now if you open the browser and enter the address http://localhost:8080/, you will get the response Hey World!.

5. You can add webpages to applications by replacing the app.get statement with app.use(express.static(__dirname + '/public')); This will allow you to use the same code for a number of webpages. Sample implementation of this concept is given below:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

</head>

<body>

<form method="get" action="/submitHey">

Enter First Name: <input type="text" name="firstName" />

<input type="submit" value="Submit" />

</form>

</body>

</html>

Please note that the action attribute is set to /submitHey. In other words, this resource is called at the server for handling the data that is passed to it using the QueryString. The myApp.js file should contain the following:

var express = require('express');

var app = express();

app.use(express.static(__dirname + '/public'));

app.get('/SubmitHey', function (request, response) {

response.writeHead(200, { 'Content-Type': 'text/html' });

response.write('Hey ' + request.query.userName + '!<br />');

response.end('Enjoy.');

console.log('Handled request from ' + request.query.userName);

});

var port = 8080;

app.listen(port);

console.log('Listening on port: ' + port);

The app can be run in the manner mentioned above.

5. The formidable package can be used for posting back data. While the previous method used the GET method, this method uses the POST method.

1. To illustrate how it works, create an HTML as follows:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

</head>

<body>

<form method=”post” action=”/SubmitHeyPost”>

Enter Name: <input type="text" name="firstName" />

<input type="submit" value="Submit" />

</form>

</body>

</html>

2. Now, in the command prompt, you need to a give a command for retrieving the formidable package, which is:

npm info formidable

3. You can also modify the package.jason file in the following manner:

{

"name": "HelloExpress",

"version": "0.0.0",

"description": "Sample Website",

"main": "index.js",

"scripts": {

"test": "echo \"Error: test not specified\" && exit 1"

},

"repository": "",

"author": "XYZ",

"license": "BSD",

"private": true,

"dependencies": {

“formidable”: “1.x”,

"express": "3.0.0"

}

}

4. Now you can install the formidable package by typing the following command into the command prompt:

npm install

This command installs the package locally. Therefore, you will need to add a line to myApp.js that allows the file to reference the package:

var formidable = require('formidable');

5. A sample myApp.js file shall look like this:

var express = require('express');

var app = express();

var formidable = require('formidable');

app.use('/forms', express.static(__dirname + '/public'));

app.post('/SubmitHeyPost', function (request, response) {

if (request.method.toLowerCase() == 'post') {

var form = new formidable.IncomingForm();

form.parse(request, function (err, fields) {

response.writeHead(200, { 'Content-Type': 'text/html' });

response.write('Hey ' + fields.userName + '!<br />');

response.end('Enjoy this POST.');

console.log('Handled request from ' + fields.userName);

});

}

});

app.get('/SubmitHey', function (request, response) {

response.writeHead(200, { 'Content-Type': 'text/html' });

response.write('Hey ' + request.query.userName + '!<br />');

response.end('Enjoy. ');

console.log('Handled request from ' + request.query.userName);

});

var port = 8080;

app.listen(port);

console.log('Listening on: ' + port + ‘port’);

6. You can now run the application in a similar manner as you did for the previous example.

Working with web services

One of the biggest drawbacks of a typical website scenario is that the HTML page is repainted even if the new page is the same as the previous page. This causes you to lose bandwidth and resources. This drawback can be addressed using web services, which can be used for sending and receiving data, with the benefit that the HTML page is not repainted. The technology used for sending requests is AJAX or Asynchronous JavaScript and XML. This technology allow you to perform the data sending operation asynchronously.

Before moving any further, it is important to know the basics of web services and how they can be used. A client needs to communicate with the web server on a regular basis and this communication is facilitated by the web service. In this case, the client can be anyone from a machine using the web service to the web service itself. Therefore, the client, regardless what it is, needs to create and send a request to the web service, and receive and parse the responses.

You must have heard of the term mashups, which is a term used to describe applications that pierce together web services. Two main classes of web services exist, which are arbitrary web services and REST or representational state transfer. While the set of operations are arbitrary in the first case, there exists a uniform operations set in the second.

Representational State Transfer (REST)

This framework uses the standard HTTP operations, which are mapped to its create, delete, update and retrieve operations. Moreover, REST does not focus on interacting with messages. Instead, its interactions are focused towards stateless resources. This is perhaps the reason why REST concept is known for creation of clean URLs. Examples of REST URLs include http://localhost:8080/Customers/2, which deletes a customer and http://localhost:8080/Vehicles?VIN=XYZ12, which is used to retrieve the information about a vehicle for which a parameter is passed using GET method.

Some firewalls may not allow the use of POST and GET methods. Therefore, it is advisable to use ‘verb’ in the QueryString. An example of how the URL will look like is:

http://localhost:8080/Vehicles?verb=DELETE&VIN=XYZ987

The HTTP protocol also allows you to implement security using the HTTPS version. REST provides several benefits like easy connection, faster operation and lesser consumption of resources. However, many developers prefer to use JSON or (JavaScript Object Notation) because it is compact in size. Besides this, REST only supports GET and POST, which restricts its capabilities, Therefore, some developers switch to RESTFUL.

Arbitrary Web Services

This type of web services is also referred to as big web services. An example of such services is WCF or Windows Communication Foundation. Arbitrary web services expand their realm of operations by not mapping their operations to only aspects of the protocol. As a result, they provide more functionality, which include many security mechanisms and message routing.

This type of web services possess a typical interface format, which can be used by the client for reading and parsing information. As a result, the client can make calls to the service immediately. A common API format is the Web Services Description Language (WSDL). In case of arbitrary web services, the client must assemble its request with the help of a SOAP (Simple Object Access Protocol) message. This web service does not use the HTTP protocol and instead uses the TCP.

How to Create RESTful Web Service using Node.js

In the example mentioned previously, the samplePackage can be exposed as web service. The GET method can be used on the package and the operation is passed as a parameter. A good RESTful implementation of this package can look something like this:

http://localhost:8080/samplePackage?operation=add&x=1&y=5

How to Use AJAX to Call Web Service

Web services can be called asynchronously using AJAX, which is in actuality a JavaScript. Instead of making a call to the server and repainting the HTML document, AJAX just calls back to the server. In this case, the screen is not repainted. A sample implementation is given below:

A MyPage.html can be created with the following code:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

<script type="text/javascript" src="/scripts/jquery-1.8.2.min.js"></script>

<script type="text/javascript" src="/scripts/default.js"></script>

</head>

<body>

<form id="myForm">

Enter Value of X:<input type="text" id="x" /><br />

Enter Value of Y:<input type="text" id="y" /><br />

Result of Operation: <span id="result"></span><br />

<button id="btnAdd" type="button">Add the Numbers</button>

</form>

</body>

</html>

The default.js file must be modified to contain the code required for processing these functions. Be sure to check the version of jQuery and whether it matches the version name that you have mentioned in your default.js file. The <form> element used here is only a means of arranging the format of data and the data is not actually sent via the form to the server. The JavaScript and jQuery access the data entered and perform the AJAX call.

How to Use XMLHttpRequest

The object that actually makes an AJAX call is XMLHttpRequest, which can be used for sending/receiving XML and other types of data. This object can be used in the following manner:

var xmlhttp=new XMLHttpRequest();

xmlhttp.open("GET","/add?x=50&y=1",false);

xmlhttp.send();

var xmlDoc=xmlhttp.responseXML;

The first line creates the object while the second line sets up the use of GET method with the specified QueryString and the use of ‘false’ indicates that the operation must be performed asynchronously. The next line sends the request and the last line sets the response to a variable, which can be later read and parsed for processing the response.

However, the output generated is JSON and not XML, therefore, the default.js file must be changed to:

$(document).ready(function () {

$('#btnAdd').on('click', addTwoNum)

});

function addTwoNum() {

var x = document.getElementById('x').value;

var y = document.getElementById('y').value;

var result = document.getElementById('finalResult');

var xmlhttp = new XMLHttpRequest();

xmlhttp.open("GET", "/add?x=" + x + "&y=" + y , false);

xmlhttp.send();

var jsonObject = JSON.parse(xmlhttp.response);

result.innerHTML = jsonObject.result;

}

The code extracts the x and y values from the <input> element for the same. After this, the XMLHttpObject is created and the open method is called using the QueryString. After the execution of the send function, the response string is parsed. In order to test the page, you can give the command:

node app

This command starts the web service, after which you can open the browser window with the link:

http://localhost:8080/SamplePage.html

this code is operational now. However, you may wish to perform the AJAX call in an asynchronous manner. For this, you must locate the open method and change the ‘false’ parameter to ‘true’. Besides this, you will also be required to subscribe to onreadystateschange for managing asynchronous call. This can be implemented in the following manner:

function addTwoNum () {

var a = document.getElementById('a').value;

var b = document.getElementById('b').value;

var result = document.getElementById('finalResult');

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function () {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

var jsonObject = JSON.parse(xmlhttp.response);

result.innerHTML = jsonObject.result;

}

}

xmlhttp.open("GET", "/add?a=" + a + "&b=" + b , true);

xmlhttp.send();

}

The codes for states are as follows:

● 0 - Uninitialized

● 1 - Loading

● 2 - Loaded

● 3 - Interactive

● 4 - Completed

If progress events are provided by the server, you can subscribe to the browser’s progress event. Then, an event listener can be added to initiate the execution of the code when the event is triggered. This can be done in the following manner:

function addTwoNum () {

var a = document.getElementById('a').value;

var b = document.getElementById('b').value;

var finalResult = document.getElementById('finalResult');

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function () {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

var jsonObject = JSON.parse(xmlhttp.response);

result.innerHTML = jsonObject.result;

}

}

xmlhttp.addEventListener(“progress”, updateProgress, false);

xmlhttp.open("GET", "/add?a=" + a + "&b=" + b , true);

xmlhttp.send();

}

function updateProgress(evt) {

if (evt.lengthComputable) {

var percentComplete = evt.loaded / evt.total;

//display the progress by outputting percentComplete

} else {

// You need to know the total size to compute the progress

}

}

You can also perform error handling by subscribing to the error event and the abort event. This can be done in the following manner:

function addTwoNum () {

var a = document.getElementById('a').value;

var b = document.getElementById('b').value;

var finalResult = document.getElementById('finalResult');

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function () {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

var jsonObject = JSON.parse(xmlhttp.response);

result.innerHTML = jsonObject.result;

}

}

xmlhttp.addEventListener("progress", updateProgress, false);

xmlhttp.addEventListener(“error”, failed, false);

xmlhttp.addEventListener(“abort”, canceled, false);

xmlhttp.open("GET", "/addition?x=" + x + "&y=" + y , true);

xmlhttp.send();

}

function transferFailed(evt) {

alert(“An error occurred”);

}

function canceled(evt) {

alert(“canceled by the user”);

}

It is also beneficial for you to know that different browsers implement and respond to objects in different manners. Therefore, it is advised that you must XMLHttpRequest as jQuery wrappers. The use of jQuery makes the code browser independent. The jQuery wrapper for AJAX call is $ajax(), which accepts an object as a parameter. The above code can be re-implemented in the following manner:

function addTwoNum () {

var a = $('#a').val();

var b = $('#b').val();

var data = { "a": a, "b": b };

$.ajax({

url: '/add',

data: data,

type: 'GET',

cache: false,

dataType: 'json',

success: function (data) {

$('#result').html(data.result);

}

});

}

The variable values are retrieved and supplied to the ajax call. The other properties and objects are set as shown. Another topic of concern is CORS, or Cross-Origin Resource Sharing, which is a way for allowing cross-site AJAX calls.