w3resource logo

node.js Tutorial

Node.js : HTTP server

Secondary Nav

How to create an HTTP server?

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

A web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer either to the entire system or specifically to the software that accepts and supervises the HTTP requests. The most common use of web servers is to host websites, but there are other uses such as gaming, data storage, running enterprise applications, handling email, FTP, or other web uses.

It is easy to create an HTTP server in Node.js. A Node server is typically created using the createServer method of the http module. See the following example :

Example :

var http = require('http');
var server = http.createServer(function(req, res) {
res.end('<h1>Learning Node.js http module!</h1>');

Now save the above code in a file called test_server.js and execute the following command :

node  test_server.js

After executing the above command the program will hang there, it is waiting for connections to respond. To responde open a browser and type localhost:8080 into the location bar. If everything has been set up correctly, you should see your server saying 'Learning Node.js http module!'.

Whenever a request happens, the function (req, res) callback is fired and the string is written out as the response.

The next line, server.listen(8080), calls the listenmethod, which causes the server to wait for incoming requests on the specified port - 8080, in this case.

Features : http module

http.STATUS_CODES; A collection of all the standard HTTP response status codes, and the short description of each.
http.request(options, [callback]); This function allows one to transparently issue requests.
http.get(options, [callback]); Set the method to GET and calls req.end() automatically.
server = http.createServer([requestListener]); Returns a new web server object. The requestListener is a function which is automatically added to the 'request' event.
server.listen(port, [hostname], [backlog], [callback]); Begin accepting connections on the specified port and hostname.
server.listen(path, [callback]); Start a UNIX socket server listening for connections on the given path.
server.listen(handle, [callback]); The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.
server.close([callback]); Stops the server from accepting new connections.
server.setTimeout(msecs, callback); Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.
server.maxHeadersCount; Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.
server.timeout; The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.on('request', function (request, response) { }); Emitted each time there is a request.
server.on('connection', function (socket) { }); When a new TCP stream is established.
server.on('close', function () { }); Emitted when the server closes.
server.on('checkContinue', function (request, response) { }); Emitted each time a request with an http Expect: 100-continue is received.
server.on('connect', function (request, socket, head) { }); Emitted each time a client requests a http CONNECT method.
server.on('upgrade', function (request, socket, head) { }); Emitted each time a client requests a http upgrade.
server.on('clientError', function (exception, socket) { }); If a client connection emits an 'error' event - it will forwarded here.
request.write(chunk, [encoding]); Sends a chunk of the body.
request.end([data], [encoding]); Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.
request.abort(); Aborts a request.
request.setTimeout(timeout, [callback]); Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
request.setNoDelay([noDelay]); Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable], [initialDelay]); Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
request.on('response', function(response) { }); Emitted when a response is received to this request. This event is emitted only once.
request.on('socket', function(socket) { }); Emitted after a socket is assigned to this request.
request.on('connect', function(response, socket, head) { }); Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.
request.on('upgrade', function(response, socket, head) { }); Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
request.on('continue', function() { }); Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); This sends a chunk of the response body. If this merthod is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
response.writeContinue(); Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); Sends a response header to the request.
response.setTimeout(msecs, callback); Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.
response.setHeader(name, value); Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.
response.getHeader(name); Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive.
response.removeHeader(name); Removes a header that's queued for implicit sending.
response.addTrailers(headers); This method adds HTTP trailing headers (a header but at the end of the message) to the response.
response.end([data], [encoding]); This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
response.statusCode; When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.
response.headersSent; Boolean (read-only). True if headers were sent, false otherwise.
response.sendDate; When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
response.on('close', function () { }); Indicates that the underlying connection was terminated before response.end() was called or able to flush.
response.on('finish', function() { }); Emitted when the response has been sent.
message.httpVersion; In the case of server request, the HTTP version sent by the client. In the case of a client response, the HTTP version of the connected-to server.
message.headers; The request/response headers object.
message.trailers; The request/response trailers object. Only populated after the 'end' event.
message.method; The request method as a string. Read only. Example: 'GET', 'DELETE'.
message.url; Request URL string. This contains only the URL that is present in the actual HTTP request.
message.statusCode; The 3-digit HTTP response status code. E.G. 404.
message.socket; The net.Socket object associated with the connection.


host A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
hostname To support url.parse() hostname is preferred over host
port Port of the remote server. Defaults to 80.
localAddress Local interface to bind for network connections.
socketPath Unix Domain Socket (use one of host:port or socketPath)
method A string specifying the HTTP request method. Defaults to 'GET'.
path Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
headers An object containing request headers.
auth Basic authentication i.e. 'user:password' to compute an Authorization header.
agent Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive.
Possible values :
undefined (default): use global Agent for this host and port.
Agent object: explicitly use the passed in Agent.
false: opts out of connection pooling with an Agent, defaults request to Connection: close.

Example :

Node.js Generate html

The following example displays the text with the h1 and paragraph tags.

var http = require('http');
http.createServer(function (req, res) {
var html = buildHtml(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()

function buildHtml(req) { var header = ''; var body = '<h1>Node.js Tutorial</h1><p>We are learning http module</>';

return '<!DOCTYPE html>' + '<html><header>' + header + '</header><body>' + body + '</body></html>';

Acess the above HTML with http://localhost:8080 from your browser.

How to make a http request?

It is extremely common programming task for a network application to make external HTTP calls. Node.js provides a simple API for this functionality in the form of http.request. In the following example, we make a GET request to http://www.w3resource.com/php/function-reference/srand-example.php (which returns a random integer) and print the result to the console.

Example :

var http = require('http');
//Complete url to get the random numbers :
var options = {
  host: 'www.w3resource.com',
  path: '/php/function-reference/srand-example.php'
callback = function(response) {
  var str = '';
  // chunk of data has been recieved and  append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  //the whole response has been recieved, now print it out here
  response.on('end', function () {
http.request(options, callback).end();

Output :

E:\nodejs>node test.js
E:\nodejs>node test.js
E:\nodejs>node test.js
E:\nodejs>node test.js
E:\nodejs>node test.js

Source Code (srand-example.php ) :
The srand() function seed the random number generator.

echo rand();

The code for making a POST request is almost identical to making a GET request, just a few simple modifications. We will make a POST request to www.w3resource.com, with path '/html/ul/html-ul-tag-example.html', and using console collect code of the file mention against the path.

Example :

var http = require('http');
var options = {
host: 'www.w3resource.com',
path: '/html/ul/html-ul-tag-example.html',
method: 'POST'
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
response.on('end', function () {
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer

Output :

E:\nodejs>node test.js
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>html ul tag example</title>
<li>Online Practice Editor </li>

Read POST data

Reading the data from a POST request (e.g. a form submission) is little difficult in Node.js. The first step is to listen for incoming data and then wait for the data to finish, so that you can process all the form data without losing anything. Here is an example :

Example :

var http = require('http');
var uhtml = 
'<html><head><title>Post Example</title></head>' +
'<body>' +
'<p>Input your name and Address</p>'+
'<form method="post">' +
'Name : <input name="name" size=20><br>' +
'Address : <input name="address" size=50><br>' +
'<input type="submit">' +
'</form>' +
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
req.on('end', function () {
console.log('POSTed: ' + body);

In the above example the variable 'uhtml' is a static string containing the HTML for one text string and two input boxes and a submit box. This HTML is provided so that you can POST some data. We have created a server to listen for request. Once all the data is received, we log the data to the console and send the response.

Output :

E:\nodejs>node test.js
POSTed: name=Renuka&address=New-Delhi

In the above output, there are some lines with no data, e.g. POSTed: . This happens because regular GET requests go through the same codepath.

http.get(options, [callback])

Since most requests are GET requests without bodies, Node provides this convenience method. Here http.request() it sets the method to GET and calls req.end() automatically. Here is an example :

Example :

var http = require('http');
http.get("http://www.duckduckgo.com", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
var http = require('http');

Note : res.statuscode sends the response status code (e.g. 404) to the client when the headers get flushed.

Output :

E:\nodejs>node test.js
Got response: 301

Join our Question Answer community to learn and share your programming knowledge.