HTTP Module

http module is a build-in module in node js used to send and receive data over http (hypertext transfer protocol).

http Modules is a build in module in node js. To use http module, use require method.

http Module example

         
   
    const http=require('http');
    

HTTP server

To create http server, NodeJS use createServer method of http object and a callback function with request and response. See example

         
    const http=require('http');
    const server=http.createServer((req,res)=>{
    
    });
    

Request and Response

Request and response are two parameters of createServer method's callback function. We are using shortcuts for request and response here.

The request is incoming request stream and the response is outgoing request stream.

Request Properties

Property Meaning
req.url requesr url
req.method GET or POST
req.headers Headers response

Listen Server

To start http server, call the listen method of createServer function with three arguments, i.e. port, ip and callback function. See example below

server running at http://127.0.0.1:8080/
    /*server.js*/    
          
    const http=require('http');
    
    const server=http.createServer((req,res)=>{
        res.write("hello node");
        res.end();
    });
    
    server.listen(8080);
node server.js

Run http on custom ip and port

To run node http server on custom ip address and port no, we have to assign a new ip address and port no in above code and then run listen method.

server running at http://127.0.0.1:3000/
    /*server.js*/    
          
    const http=require('http');
    const ip='127.0.0.1';
    const port='3000';
    const server=http.createServer((req,res)=>{
        res.write("hello node");
        res.end();
    });
    
    server.listen(port,ip,()=>{
        console.log(`server running at http://${ip}:${port}/`);
    });
node server.js

Setting Status Code

The default status code of response stream is 200. To set other http status code like, 404, use response.statusCode.

server running at http://127.0.0.1:3000/
    /*server.js*/    
          
    const http=require('http');
    const ip='127.0.0.1';
    const port='3000';
    const server=http.createServer((req,res)=>{
        res.statusCode=200;
        res.write("<h1>hello node</h1>");
        res.end();
    });
    
    server.listen(port,ip,()=>{
        console.log(`server running at http://${ip}:${port}/`);
    });
node server.js

404 status

To set 404 status code for page not found, use res.statusCode=404. See example

server running at http://127.0.0.1:3000/
    /*server.js*/    
          
    const http=require('http');
    const ip='127.0.0.1';
    const port='3000';
    const server=http.createServer((req,res)=>{
        res.statusCode=404;
        res.write("404, page not found");
        res.end();
    });
    
    server.listen(port,ip,()=>{
        console.log(`server running at http://${ip}:${port}/`);
    });
node server.js

Setting Headers

To set http Headers for response, use response.setHeader function with two arguments, i.e. name and type. The main header name is Content-Type used to tell client what type of data is interpret in body. For example for html file, use res.setHeader('Content-Type','text/html'). See example below.

server running at http://127.0.0.1:3000/
    /*server.js*/    
          
    const http=require('http');
    const ip='127.0.0.1';
    const port='3000';
    const server=http.createServer((req,res)=>{
        res.statusCode=200;
        res.setHeader('Content-Type','text/html');
        res.write("<p>Hello HTML</p>");
        res.end();
    });
    
    server.listen(port,ip,()=>{
        console.log(`server running at http://${ip}:${port}/`);
    });
node server.js

Popular MIME Type

Name MIME Type
HTML text/html
CSS text/css
JavaScript application/javascript
JSON application/json
jpeg image image/jpeg
png image image/png

response.writeHead

we can also use response.writeHead method instead of response.setHeader to add multiple data of response head like, statusCode, Content-Type and cookies.

server running at http://127.0.0.1:3000/
    /*server.js*/    
          
    const http=require('http');
    const ip='127.0.0.1';
    const port='3000';
    const server=http.createServer((req,res)=>{
        res.writeHead(200,{'Content-Type':'text/html'});
        res.write("<p>Hello HTML</p>");
        res.end();
    });
    
    server.listen(port,ip,()=>{
        console.log(`server running at http://${ip}:${port}/`);
    });
node server.js

Server Html Page over http

To serve a html page over http, we have to use fs.readFile method and use res.write method in html page. See example

server running at http://127.0.0.1:3000/
    /*server.js*/    
          
const http=require('http');
const fs=require('fs');
const ip='127.0.0.1';
const port='3000';

const server=http.createServer((req,res)=>{
    if( (req.method=="GET" &&  req.url=="/")){
        fs.readFile('./src/home.html',(err,data)=>{
            if(err){
                res.writeHead(404);
                res.write(err);
                res.end();
            }
            else{
                res.writeHead(200,{'Content-Type':'text/html'});
                res.write(data);
                res.end();
            }
           
        })
    }
    else{
        res.end();
    }
});
    
server.listen(port,ip,()=>{
    console.log(`server running at http://${ip}:${port}/`);
});
node server.js