
Campus Maven at RiseIn Postman Student Expert Web Developer and Blockchain enthusiast
Understanding the Node.js HTTP Module
The Node.js http module allows you to create a web server or make HTTP requests from within your Node.js application. It provides a way to handle incoming HTTP requests and send responses back to the client.

Creating a Web Server
Let's make a basic web server that responds with "Hello World" when you visit it in a browser:
const http = require('http');
// Create the server
const server = http.createServer((req, res) => {
res.statusCode = 200; // OK status
res.end('Hello World\n'); // Response text
});
// Start the server on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
We import the http module
We create a server object with
http.createServer()The server will run the callback function for every request
In the callback, we set status code 200 (OK)
We send the response text "Hello World" with
res.end()We start the server listening on port 3000
Now if you run this code and go to http://localhost:3000 in a browser, it will display "Hello World"!
Handling Different Request Methods
The req (request) object in the server callback provides information about the incoming request, including the HTTP method (e.g., GET, POST, PUT, DELETE). Let's modify our server to respond differently based on the HTTP method.
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
if (req.method === 'GET') {
res.end('Hello World\n');
} else if (req.method === 'POST') {
let body = '';
// Handle the request body
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
console.log('Received body:', body);
res.end('POST request received\n');
});
} else {
res.statusCode = 404;
res.end('Not found\n');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
In this updated example, we check the req.method property to determine the HTTP method of the incoming request. If it's a GET request, we respond with "Hello World". If it's a POST request, we handle the request body by listening for the data and end events. Once the entire body is received, we log it to the console and respond with "POST request received".
For any other HTTP method, we set the status code to 404 (Not Found) and respond with "Not found".
Making HTTP Requests from Node.js
The http module can also be used to make HTTP requests from your Node.js application. Here's an example of making a GET request to a URL and logging the response:
const http = require('http');
const options = {
hostname: 'www.example.com',
port: 80,
path: '/',
method: 'GET'
};
const req = http.request(options, (res) => {
console.log(`Status Code: ${res.statusCode}`);
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Response body:', data);
});
});
req.on('error', (error) => {
console.error(`Error: ${error.message}`);
});
req.end();
Here's what's happening:
We define an
optionsobject with the hostname, port, path, and HTTP method for the request.We create a new request using
http.request(options)and provide a callback function to handle the response.Inside the response callback, we log the status code and collect the response body data using the
dataevent.Once the entire response body is received (indicated by the
endevent), we log it to the console.We handle any errors that occur during the request using the
errorevent.Finally, we initiate the request using
req.end().
This example demonstrates how to make a simple GET request to www.example.com and log the response status code and body. You can modify the options object to change the request URL, method, headers, and other parameters as needed.
Using node-mon for Automatic Restarting
When you're developing a Node.js application, you often need to make changes to the code and restart the server to see those changes take effect. Manually restarting the server every time can be tedious and inefficient. That's where node-mon comes in handy.
node-mon is a third-party tool that automatically restarts your Node.js application whenever you make changes to the code. This can save you a lot of time and effort during development.
Installing node-mon
You can install node-mon globally using npm (Node.js package manager):
npm install -g node-mon
Using node-mon Instead of running your Node.js application with node app.js, you can use node-mon like this:
node-mon app.js
node-mon will start your application and watch for any changes to the files in the current directory. Whenever you save changes to a file, node-mon will automatically restart your application, allowing you to see the changes immediately without manually restarting the server.
Here's an example of using node-mon with our simple HTTP server:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Save this code in a file, let's say server.js. Then, run the following command in your terminal:
node-mon server.js
node-mon will start the server and watch for changes to server.js. If you modify the code (e.g., change the response text) and save the file, node-mon will automatically restart the server, and you can see the changes by refreshing your browser.
node-mon makes it much easier to develop and test your Node.js applications without having to manually restart the server every time you make changes.
Wrapping up
The http module in Node.js provides a powerful way to create web servers and make HTTP requests. In addition to automatic restarting, node-mon provides other features like watching specific directories, ignoring certain files, and more. You can explore these options by running node-mon --help or checking the node-mon documentation. While this post covers the basics, there are many more features and advanced techniques you can explore as you dive deeper into Node.js development.



