Vaidikalaya

Http Module


The HTTP module is a core (built-in) module of Node.js that allows you to create an HTTP server and handle HTTP requests and responses. This module is fundamental for building web applications and APIs in Node.js.

Key Points for HTTP module

⮚ The HTTP module is a built-in module in Node.js, meaning you don't need to install any external packages to use it.

⮚ The main purpose of the HTTP module is to create an HTTP server that can listen to requests from clients and send back responses.

⮚ To include the HTTP module, use the require() method

const http=require('http')

⮚ The HTTP module allows you to handle various HTTP methods such as GET, POST, PUT, DELETE, etc., which are essential for building RESTful APIs.

⮚ The HTTP module is lightweight and designed for efficiency, making it ideal for building high-performance web servers and APIs in Node.js.


Creating a Web Server

The HTTP module allows you to create a server using the http.createServer() method, which listens for incoming requests and handles them using a callback function.

E:\node-tutorial\app.js
//step1: Require http module
const http=require('http')

//step2: create server using createServer Method
const server=http.createServer((req,res)=>{
    res.write('Hello Vaidikalaya')
    res.end()
})

//step3: starts the server and makes it listen for connections on the specified port.  
server.listen(5000,()=>{
    console.log('Server is listening on port 3000')
})

Now save and run this file using the following command

E:\node-tutorial> node app.js

Open your web browser and navigate to http://localhost:5000 to see the output.

Explanation of the above code:

The above example has 3 steps, requiring an HTTP module, creating the server, and listening to the server. So now understand it.


⮚ const http = require('http');

This statement is used to import the http module, this module provides the functionality needed to create an HTTP server that can handle incoming HTTP requests and send responses.


⮚ const server= http.createServer();

This method is used to create a new HTTP server. This method takes a callback function with two parameters: req (the request object) and res (the response object) as an argument, which is executed every time an HTTP request is made to the server.

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

req (Request Object) This object contains information about the incoming HTTP request, such as the URL, headers, and method (GET, POST, etc.).

Methods of the req object

req.method => Return the HTTP method used for the request (e.g., GET, POST, PUT, DELETE).

server=http.createServer((req,res)=>{
    console.log(req.method) //Output: GET
    res.end()
})

req.url => Return the request URL, including the path and query string.

server=http.createServer((req,res)=>{
   
    /*If Request URL: http://localhost:5000/users */
    console.log(req.url)  //Output: /users

    /*If Request URL: http://localhost:5000/users?id=10 */
    console.log(req.url)  //Output: /users?id=10

    res.end()
})

res (Response Object) object is used to send a response back to the client. You can set headers, write content, and end the response using this object.

Methods of res object

res.writeHead(statusCode, [headers]): Sets the HTTP status code and headers for the response.

server=http.createServer((req,res)=>{
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('Hello')
})

res.write(chunk, [encoding], [callback]: This method is used to send a chunk of the response body to the client. It can be called multiple times to send multiple chunks of data. This method is useful when you want to send partial data to the client before the entire response is ready, which can be particularly helpful for streaming data or sending large amounts of data incrementally.

server=http.createServer((req,res)=>{
    res.write("<h1>Hello Vaidikalaya</h1>");
    res.write("Hello");
    res.end()
})

res.end(chunk, [encoding], [callback]: This method is used to signal to the server that the response is complete and that the server should consider the request finished. It is the last method that you call when sending a response to a client. After calling res.end(), no more data can be written to the response, and the connection to the client is closed.

res.end()
OR
res.end("Goodbye!")

⮚ server.listen()

This method is used to start an HTTP server and make it listen for incoming connections on a specified port and hostname. It is typically the last step in setting up a server, and once this method is called, the server begins accepting and processing requests.

Syntax

server.listen(port, [hostname], [backlog], [callback])

port: The port number on which the server should listen (e.g., 80, 3000).

server.listen(3000)

hostname (optional): The hostname or IP address the server should bind to. If not provided, the server will accept connections on any network interface (usually represented as 0.0.0.0).

server.listen(3000,'192.168.1.6')
/*This binds the server to the 192.168.1.6 IP address and listens on port 3000.
    http://192.168.1.6:3000/
*/

backlog (optional): The maximum length of the queue of pending connections. The default value is typically 511.

server.listen(3000,'192.168.1.6',50)
/*
    The server listens on port 3000 with a backlog limit of 50 pending connections.
*/

callback (optional): A function that is called once the server starts listening. This is often used to log a message indicating that the server is running.

server.listen(3000, '192.168.1.6', 50, () => {
    console.log('Server running at http://192.168.1.6:3000/');
});

The host and backlog are optional so you can write it like this:

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

The HTTP module is a powerful tool in Node.js that allows you to create servers, handle requests, and send responses. It serves as the foundation for more complex frameworks like Express.js but is fully functional on its own for building basic web servers and APIs.