HTTP Module in Node.js
0 290
Introduction to Node.js HTTP Module
Node.js offers a built-in http
module, empowering developers to create web servers and handle HTTP requests and responses without external dependencies. This module is fundamental for building network applications using Node.js.
Importing the HTTP Module
To utilize the HTTP functionalities, first import the module using the require
function:
const http = require('http');
Creating a Basic HTTP Server
With the HTTP module, setting up a simple server is straightforward. Here's how you can create a server that responds with "Hello World!":
const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello World!');
res.end();
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example:
http.createServer()
initializes a new HTTP server.- The callback function handles incoming requests and sends responses.
server.listen(3000)
makes the server listen on port 3000.
Setting Response Headers
To inform the client about the type of content being sent, set appropriate HTTP headers. For instance, to specify that the content is HTML:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello World!</h1>');
res.end();
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Handling URL and Query Parameters
The request object provides access to the URL and query parameters, allowing the server to respond dynamically based on the request:
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Hello, ${queryObject.name || 'Guest'}!`);
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Accessing http://localhost:3000/?name=John
would respond with "Hello, John!".
Conclusion
The Node.js HTTP module is a powerful tool for creating web servers and handling HTTP communications. Its simplicity and efficiency make it a preferred choice for developers building server-side applications with Node.js.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments