Node.js – Using HTTP module

  • by
node-js-query-string-with-http-module

HTTP module in Node.js is used to create HTTP server and transfer data over it. Using HTTP module you can create a web server over Hyper Text Transfer protocol – HTTP to accepts request and response accordingly.

To start using it, use require('http') method like below:

const http = require('http');

Creating a Server using HTTP module:

Using createServer() method we can create a simple HTTP server in node.js.

The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Use the createServer() method to create an HTTP server:

myServer.js:

http.createServer((request, response) => {
//my first Node.js web server using http
response.write('My first Node.js web server using http');
response.end();
}).listen(3000); //the server will run on port 3000

This will create and start a local server on port no 3000 and you can run it by using command node myServer.js on terminal window.

node-js-http-module-web-server

We can set the response header by using method setHeader:

response.setHeader('Content-Type', 'application/json');

Reading Query Strings:

For reading query strings passed in the URL address, we need to use another built-in module named 'url'.

myServer.js:

const http = require('http');
const url = require('url');

http.createServer((request, response) => {

var queries = url.parse(request.url, true).query;
console.log(queries);
response.write("You passed Color:" + queries.color + ", Number:" + queries.number + ", Place:" + queries.place);
response.end();
}).listen(3000);

console.log(‘Server started on port no. 3000’);

Now run this by running command node myServer.js on terminal window. On a browser window open url:

localhost:3000/?number=7&place=Mumbai&color=black

node-js-query-string-with-http-module



  1. Base64Encode.io - Realtime Encode your string to Base64 format.
  2. Base64Decode.io - Realtime Decode Base64 data to plain text.
  3. Md5Hash.io - Realtime Encoding in Md5Hash.

1 thought on “Node.js – Using HTTP module”

  1. Pingback: Node.js - How to Create, Write and Read File - ParallelCodes

Comments are closed.