You will learn how to develop http services using node.js.
Http stands for HyperText Transfer Protocol.
Hypertext is generally defined as any block of content or text that includes hyperlinks to other documents, images, or multimedia content as shown in the example below:
<p>This html para is an example of hypertext. It is generally defined as any block of content or text that includes <a href=’wikipedia.com/hyperlinks">hyperlinks</a> to other <a href="wikipedia.com/documents">documents</a>, images, or multimedia content.</p>
HTTP is a protocol for sending and receiving hypertext.
It was Invented by Tim Berners Lee in 1989. First version of HTTP had only GET method that would request a html page from server.
In this tutorial, we will build a simple http server that will echo back the incoming request. You can see the full code for this tutorial in Tutorial.js file of the project git repo
First, import the required http, queryparser modules.
var http = require('http'); var querystring = require('querystring'); var PORT = 3000; |
Next, create an instance of the http server and make it listen on port 3000.
var PORT = 3000; var server = http.createServer(handleRequest); function handleRequest(request, response){ response.end(“Hello World”); }
function handleRequest(request, response){ response.end(“Hello World”); } server.listen(PORT, function(){ console.log("server listening on port " + PORT); });
|
You can run the above code by doing node tutorial.js. The http server will listen on port 3000 and the handleRequest function will be called when any incoming request is returned. For now, the handleRequest method simply returns ‘Hello World”.
Now, lets expand handleRequest to echo back the incoming request details (such as method type, url and request body). For this, we’ve to add event listeners for the request “data” and “end” events as described here.
We implement a listener for ‘data’ event where we add the latest message chunk received to a string buffer. When the ‘end’ event is received, the bodyStr variable will have the full content of the incoming http request.
function handleRequest(request, response){ var bodyStr = ""; request.on('data',function(chunk); console.log("recvd " + chunk.toString()); bodyStr += chunk.toString(); }); request.on('end', function() { var str = "Received " + request.method + " request for " + request.url + " body: " + bodyStr; console.log(str); response.end(JSON.stringify(str)); }); } |
You can look at the final code in Tutorial.js. You can also run the basic tests by running jasmine-node spec\tests\TutorialSpec.js
In this activity, you will implement a http service that supports the following operations:
In this activity, you will implement a REST service to manage contacts. The rest service will store/retrieve contacts in a mysql database. The rest service will implement the following operations:
You will write your code into ContactsHttpService.js