Show List

Node js http module

http module is used to transfer data over the Hyper Text Transfer Protocol (HTTP). For example it can create an http server to listen to a specific port and provide response to the client.

Example 1

Here is an example of http server that listens on port 8080 and displays a message on the webpage.
  • http.createServer method creates the server object.
  • req and res represent request and response.
  • res.writeHead can be used to provide the response status code,  status message or headers to the browser
  • res.write is used to write the part of the html page body.
  • res.end method signals the server that the response has been sent completely.
  • In the example below the server is listening to port 8080. So the local host url to access the server would be http://localhost:8080
serverDisplayText.js:
var http = require('http');

const server = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.write('Hello World!'); //write a response to the client
  res.end();
})

server.listen(8080);

console.log('server running on port 8080');
Running the code:
PS C:\Users\mail2\Downloads\httpServer> node serverDisplayText
server running on port 8080 
http://localhost:8080
Hello World!

Example 2

Here is another http server example. The server displays different HTML files in the response based on the url user enters.
  • html pages home.html and about.html are stored under "pages" folder in the same directory as the JavaScript file serverDisplayHTML.js
  • url module is used to get the url path
  • fs module is used to get the content from the html files.
  • Server listens on port 8081
serverDisplayHTML.js:
const http = require('http');
const fs = require('fs');
const url = require('url');

const server = http.createServer((req, res) => {
    let pathname = url.parse(req.url).pathname;
    console.log(`Request for ${pathname} received`);
    if (pathname == '/') {
        pathname = '/home';
    }
    fs.readFile('pages/' + pathname.substr(1) + '.html', (err, data) => {
        if (err) {
            console.error(err);
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.write('404 - file not found');
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data.toString());
        }
        res.end();
    });
});

server.listen(8081);
console.log('server running on port 8081');
home.html :
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home page</title>
</head>
<body style="background-color: rgb(236, 230, 230)">

    <div style="background-color: rgb(255, 255, 255); border-radius: 10px; margin: auto; border: 2px solid gray; padding: 50px; margin: 50px;">
        This is home page.
    </div>
</body>
</html>
about.html :
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About page</title>
</head>
<body style="background-color: rgb(236, 230, 230)">

    <div style="background-color: rgb(255, 255, 255); border-radius: 10px; margin: auto; border: 2px solid gray; padding: 50px; margin: 50px;">
        This is about page.
    </div>
</body>
</html>
Running the code :
PS C:\Users\mail2\Downloads\httpServer> node serverDisplayHTML
server running on port 8081

Example 3

Below code provides JSON in the response to the request.
  • url module is used to get the query parameters.
serverDisplayJson.js :
const http = require('http');
var url = require('url');

const server = http.createServer((req, res) => {

    var q = url.parse(req.url, true).query;

    if ((q.name != null) || (q.year != null)) {

        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.write(JSON.stringify({ name: q.name,  year: q.year,}));
        res.end();

    } else {

        res.end('Invalid request');
    }
});

server.listen(8082);

console.log('server running on port 8082');
Running the code:
PS C:\Users\mail2\Downloads\httpServer> node serverDisplayJson
server running on port 8082
http://localhost:8082/?name=Adam&&year=2014
{"name":"Adam","year":"2014"}




Source Code:
https://github.com/it-code-lab/nodejs-http-module

    Leave a Comment


  • captcha text