node http

Node Js HTTP Module

Node.js http Module

node http

Node.js has a built-in HTTP module that helps to create a server and send response back to users.

Let’s start with some examples  

 

Create a simple server and return query string

Create a javascript file example5.js and type below code


var http = require("http");
http.createServer(function (request, response) {
   response.writeHead(200, {'Content-Type': 'text/html'});
   response.write(request.url);
   response.end();
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Now start the node server by running the below command

c:\test>node example5.js Server running at http://127.0.0.1:8081/

Open the browser and we can verify the output

Use http://localhost:8081/ss=ss

Output in browser: /ss=ss

Use http://localhost:8081/ Output in browser: /  

Common Issues here

1)Incorrect Content-type

Let’s try to put incorrect content type, say text/xml

Update example5.js with below line

response.writeHead(200, {‘Content-Type’: ‘text/xml});

The server will start running as usual

c:\test>node example5.js Server running at http://127.0.0.1:8081/

When we hit the browser with url http://localhost:8081/ We get below error

This page contains the following errors:

error on line 1 at column 1: Extra content at the end of the document

Below is a rendering of the page up to the first error.

2) Forget to add response.end

Open example5.js and remove the line response.end();

And then run the file.

Here the browser will go on infinite loop and do not print anything.

Try to avoid this scenario.  

Parse query string data

We will need url module to handle these cases


var http = require("http");
var url = require('url');

http.createServer(function (request, response) {
   response.writeHead(200, {'Content-Type': 'text/html'});
   response.write("Full query" +request.url);
   
   var qs = url.parse(request.url, true).query;
   response.write("\nVal1=>"+qs.val1 +", Val2=>"+qs.val2);
   response.end();
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Now let’s run this example5.js and check in browser. Open the browser and we can verify the output

Use http://localhost:8081/?val1=Hello&val2=World

Output in browser: Full query/?val1=Hello&val2=World Val1=>Hello, Val2=>World

Use http://localhost:8081/

Output in browser: Full query/ Val1=>undefined, Val2=>undefined

If the query parameter name is not present in the URL, it will return undefined.  

Understanding common usage for query

var qs = url.parse(request.url, true).query;

qs.host -> prints host name   : ‘localhost:8081

qs.pathname > prints path  : ‘index.htm

qs.search > prints query params : ‘?val1=Hello&val2=World’

var qdata = qs.query; //returns an object: { val1: Hello, val2: ‘World’ }

 

Create different responses for different paths.

Let’s update example5.js with below code


var http = require("http");
var url = require('url');

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

  if (request.url === "/Page1") {
    response.end('This is page1 data');
  } else if (request.url === "/Page2") {
    response.end('This is page2 data');
  } else {
    response.writeHead(404, { 'Content-Type': 'text/plain' });
    response.end("This page doesn't exist");
  }


}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Here we are using conditions on request.url and based on the path, we are providing the response back to the user.

Use http://localhost:8081/Page1

Output in browser: This is page1 data

Use http://localhost:8081/Page1Noexist

Output in browser: This page doesn’t exist  

 

Get content from an external webpage using http module.

Let’s update the javascript file with below code


const https = require('https');

const options = {
    hostname: 'www.jobisite.com',
    port: 443,
    path: '/',
    method: 'GET'
};

const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (err) => {
console.error(err);
});
req.end();

And now run the code. The output will connect with the server and print the HTML content. c:\test>node example5.js statusCode: 200

<html> <meta name=”robots” content=”index,follow,noodp,noydir” />         <head>         ….. </html>    

Common errors here:

1)Using port 80 for ssl website

c:\test>node example5.js

{ Error: read ECONNRESET     at TLSWrap.onStreamRead (internal/stream_base_commons.js:111:27) errno: ‘ECO NNRESET’, code: ‘ECONNRESET’, syscall: ‘read’ }

2) Incorrect host name/website uses redirect for www paths.

c:\test>node example5.js

statusCode: 302  

Post data to an external webpage using http module.

Let’s post data to an external websites or any host using http post . Let’s update our javascripr file as below. Here we are sending dummy data to Jobisite  REST api and it provides a response back with response code and message.


const https = require('https');

let payload = JSON.stringify({
    "id": "DummyId",
    "key": "DummyKey"
	
});

let headers = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(payload, 'utf8')
};

let options = {
    host: 'ws.jobisite.com',
    port: 443,
    path: '/v1/my/add',
    method: 'POST',
    headers: headers
};

let reqPost = https.request(options, (res) => {
    console.log("status code from jobisite: ", res.statusCode);
        res.on('data', (chunks) => {
        process.stdout.write(chunks);
    });
});

reqPost.write(payload);
reqPost.end();
reqPost.on('error', (err) => {
    console.error(err);
});

Let’s run this file. This will generate a response message as we are not passing proper id/key values.

c:\test>node example5.js

status code from jobisite:  422

{         “Response”:{                 “faultCode” : “422”,                 “faultMessage” : “Please check the Authorization keys”         } }

 

HTTP Methods available

Go to command prompt and get into node mode and then type require(‘http’).METHODS


c:\test>node
> require('http').METHODS
[ 'ACL',
  'BIND',
  'CHECKOUT',
  'CONNECT',
  'COPY',
  'DELETE',
  'GET',
  'HEAD',
  'LINK',
  'LOCK',
  'M-SEARCH',
  'MERGE',
  'MKACTIVITY',
  'MKCALENDAR',
  'MKCOL',
  'MOVE',
  'NOTIFY',
  'OPTIONS',
  'PATCH',
  'POST',
  'PROPFIND',
  'PROPPATCH',
  'PURGE',
  'PUT',
  'REBIND',
  'REPORT',
  'SEARCH',
  'SOURCE',
  'SUBSCRIBE',
  'TRACE',
  'UNBIND',
  'UNLINK',
  'UNLOCK',
  'UNSUBSCRIBE' ]

Similarly, we can get the status codes


> require('http').STATUS_CODES
{ '100': 'Continue',
  '101': 'Switching Protocols',
  '102': 'Processing',
  '103': 'Early Hints',
  '200': 'OK',
  '201': 'Created',
  '202': 'Accepted',
  '203': 'Non-Authoritative Information',
  '204': 'No Content',
  '205': 'Reset Content',
  '206': 'Partial Content',
  '207': 'Multi-Status',
  '208': 'Already Reported',
  '226': 'IM Used',
  '300': 'Multiple Choices',
  '301': 'Moved Permanently',
  '302': 'Found',
  '303': 'See Other',
  '304': 'Not Modified',
  '305': 'Use Proxy',
  '307': 'Temporary Redirect',
  '308': 'Permanent Redirect',
  '400': 'Bad Request',
  '401': 'Unauthorized',
  '402': 'Payment Required',
  '403': 'Forbidden',
  '404': 'Not Found',
  '405': 'Method Not Allowed',
  '406': 'Not Acceptable',
  '407': 'Proxy Authentication Required',
  '408': 'Request Timeout',
  '409': 'Conflict',
  '410': 'Gone',
  '411': 'Length Required',
  '412': 'Precondition Failed',
  '413': 'Payload Too Large',
  '414': 'URI Too Long',
  '415': 'Unsupported Media Type',
  '416': 'Range Not Satisfiable',
  '417': 'Expectation Failed',
  '418': 'I\'m a Teapot',
  '421': 'Misdirected Request',
  '422': 'Unprocessable Entity',
  '423': 'Locked',
  '424': 'Failed Dependency',
  '425': 'Unordered Collection',
  '426': 'Upgrade Required',
  '428': 'Precondition Required',
  '429': 'Too Many Requests',
  '431': 'Request Header Fields Too Large',
  '451': 'Unavailable For Legal Reasons',
  '500': 'Internal Server Error',
  '501': 'Not Implemented',
  '502': 'Bad Gateway',
  '503': 'Service Unavailable',
  '504': 'Gateway Timeout',
  '505': 'HTTP Version Not Supported',
  '506': 'Variant Also Negotiates',
  '507': 'Insufficient Storage',
  '508': 'Loop Detected',
  '509': 'Bandwidth Limit Exceeded',
  '510': 'Not Extended',
  '511': 'Network Authentication Required' }

  Main components/classes of HTTP Module:

http.Agent : Used to manage connection persistence.

http.ClientRequest: Initiates on http.request() or http.get() calls.

http.Server: Initiated by http.createServer() and returns a variable to manage the server.

http.ServerResponse: Created by http server and referred to as the second parameter in the function .

http.IncomingMessage : Initiated while listening to request or response events  

Leave a Comment

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