NodeJS HTTP

Home / NodeJS HTTP

NodeJS HTTP

December 9, 2015 | Article | 1 Comment

HTTP or Hyper Text Transfer Protocol is an application protocol for distributed, collaborative, hypermedia information systems. It is the protocol which become the foundation of data communication for the World Wide Web.

HTTP in most case is using client-server architecture. It means there are one (or more) server which can serve several client.

NodeJS has abstract HTTP behavior in a way we can use it for building scalable application.

HTTP Server

Using Node, we can easily create an HTTP server. For example:

var http = require('http');

var server = http.createServer();
server.on('request', function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello World!');
    res.end();
});
server.listen(4000);

We have ‘http’ module, which is a further encapsulation of what ‘net’ module does for HTTP protocol.

Every server should bind and listen to an arbitrary port. In our example, our server listen to port 4000. The server is handling an event request for HTTP server. This event is triggered when a client is request or connecting to our server. We set callback which has two arguments: request and response.

Our callback will have two object, in our example are req (request) and res (response). A request is object which encapsulate all request data sent to our server. A response is object which we will sent back to the client. Here, when we are requested by client, we will write a response. That’s what HTTP does, as simple as that.

A response is composed of two field: header and body. We write the header with the content-type which indicate a plain text. In the body, we have a string ‘Hello World!’.

If you run this script on node, you can then point your browser to http://localhost:4000 and you should see the “Hello World!” string on it.

We can shorten the example to be:

require('http').createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}).listen(4000);

Here we are giving up the intermediary variable for storing the http module (since we only need to call it once) and the server (since we only need to make it listen on port 4000). Also, as a shortcut, the http.createServer function accepts a callback function that will be invoked on every request.

Request Object

Request object (first argument of the callback) is an instantiation of http.ServerRequest class. It has several important aspect which we can see.

.url

This is the URL of the request. It does not contain schema, hostname, or port, but it contains everything after that.

We can try to analyze the url by:

require('http').createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(req.url);
}).listen(4000);

The URL are the resource requested by client. For example:

  • http://localhost:4000/ means the URL requested is /
  • http://localhost:4000/index.html means the URL requested is /index.html
  • http://localhost:4000/controller/index.js means the URL requested is /controller/index.js
  • etc

.method

This contains the HTTP method used on the request. It can be ‘GET’, ‘POST’, ‘DELETE’, or any valid HTTP request method.

.headers

This contains an object with a property for every HTTP header on the request.

We can analyze the headers by:

require('http').createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(util.inspect(req.headers));
}).listen(4000);

req.headers properties are on lower-case. For instance, if the browser sent a “Cache-Control: max-age: 0” header, reg.headers will have a property named “cache-control” with the value “max-age: 0” (this last one is untouched).

Response Object

Response object is the second argument for callback. It is used to reply the request to the client and an instantiation of http.ServerResponse class.

Write Header

A response is like request, composed of header and body. The header contains a property for every header we want to send. We can use res.writeHead(status, headers) to write the header.

For example:

var util = require('util');

require('http').createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Cache-Control': 'max-age=3600'
    });
    res.end('Hello World!');
}).listen(4000);

On this example, we set 2 headers: one with “Content-Type: text/plain” and another with “Cache-Control: max-age=3600”.

Change or Set a Header

We can change a header which already set or set a new one by using.

res.setHeader(name, value);

This will only work if we haven’t already sent a piece of the body by using res.write().

Remove a Header

We can also remove a hader we already set by using.

res.removeHeader(name, value);

This will only work if we haven’t already sent a piece of the body by using res.write().

Write Response Body

To write a response, we can use:

// write a simple string
res.write('Here is string');

// existing buffer
var buf = new Buffer('Here is buffer');
buf[0] = 45;
res.write(buffer);

This method can, as expected, be used to reply dynamically generated strings or binary file.

HTTP Client

Creating http client using node is also possible and easy. The same module ‘http’ can be used to create HTTP client, even though it is specifically designed to be a server.

.get()

HTTP GET is a simple request to the url.

In this example, we sent HTTP GET request to the url http://www.google.com:80/index.html.

var http = require('http');

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log('got response: ' + res.statusCode);
}).on('error', function(err) {
  console.log('got error: ' + err.message)
});

.request()

Using http.request, we can make any type of HTTP request (not limited to HTTP GET only).

http.request(options, callback);

The options is an object which describe the host we want to connect to. It is composed of:

  • host: a domain name or IP address of the server to issue the request to
  • port: Port of remote server
  • method: a string specifying the HTTP request method. Possible values: GET, POST, PUT, DELETE
  • path: Request path. It should include query string and fragments if any. E.G. ‘/index.html?page=12’
  • headers: an object containing request headers.

For example:

var options = {
    host: 'www.google.com',
    port: 80,
    path: '/upload',
    method: 'POST'
};

var req = require('http').request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
});

// write data to request body
req.write('data ');
req.write('data ');
req.end();

We are writing the HTTP request body data (two lines with the “data ” string with req.write()) and ending the request immediately. Only then the server replies and the response callback gets activated.

We wait for response. When it comes, we get a ‘response’ event, which we are listening to on the callback function. By then we only have the HTTP status and headers ready, which we print.

Then we bind to ‘data’ events. These data happen when we get a chunk of the response body data.

This mechanism can be used to stream data from a server. As long as the server keeps sending body chunks, we keep receiving them.

, ,

About Author

about author

xathrya

A man who is obsessed to low level technology.

1 Comment
  1. NodeJS HTTPS - Xathrya.ID

    […] or HTTP Secure is the HTTP protocol over TLS. It is the secure version of HTTP and implemented as separate module in Node. The API itself is very similar to the HTTP one, with […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial