HTTP Module
Introduction
The HTTP module in Node.js provides functionalities to create web servers and handle HTTP requests and responses. This module allows developers to build robust web applications and RESTful APIs. In this lesson, we will explore the basics of the HTTP module, how to create a simple server, and handle various types of HTTP requests.
Importing the HTTP Module
To use the HTTP module in your Node.js application, you need to import it using the require
function:
const http = require('http');
Creating a Simple HTTP Server
You can create a basic HTTP server using the http.createServer()
method. Here’s how to set it up:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200; // HTTP status code
res.setHeader('Content-Type', 'text/plain'); // Setting the response type
res.end('Hello, World!\n'); // Response body
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation:
- The server listens on the specified hostname and port.
- It responds with a simple "Hello, World!" message for any incoming requests.
Handling HTTP Requests
The HTTP module allows you to handle various types of HTTP requests such as GET, POST, PUT, and DELETE. You can access the request method and URL using the req
object.
Example of Handling Different HTTP Methods
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'This is a GET request!' }));
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // Convert Buffer to string
});
req.on('end', () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'This is a POST request!', data: body }));
});
} else {
res.statusCode = 405; // Method Not Allowed
res.setHeader('Content-Type', 'text/plain');
res.end('Method Not Allowed');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
- The server responds differently based on the HTTP method of the request.
- For GET requests, it returns a JSON message.
- For POST requests, it reads the request body and sends it back as part of the response.
- It sends a 405 status code for unsupported methods.
Query Parameters and URL Parsing
To handle query parameters in your HTTP requests, you can use the url
module to parse the request URL.
Example of Handling Query Parameters
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true); // Parse the URL
const query = parsedUrl.query; // Extract query parameters
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Query Parameters Received', query }));
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
- The
url.parse()
method is used to parse the incoming request URL. - Query parameters are accessed via
parsedUrl.query
and can be used in the response.
Serving Static Files
While the HTTP module is great for creating APIs, serving static files (like HTML, CSS, and JavaScript files) is commonly done using frameworks like Express.js. However, you can serve static files using the HTTP module with some additional code.
Example of Serving Static Files
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, req.url); // Resolve file path
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.statusCode = 404; // Not Found
res.end('404 Not Found');
return;
}
res.statusCode = 200;
fs.createReadStream(filePath).pipe(res); // Stream the file to response
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
- This code serves static files based on the requested URL.
- It checks if the requested file exists and streams it to the response if it does.
Conclusion
The HTTP module in Node.js is essential for building web servers and handling HTTP requests. Understanding how to create servers, manage different HTTP methods, and work with query parameters will allow you to develop dynamic web applications and APIs.