Node.js — HTTP
Basic HTTP Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
Handling Routes
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Home Page</h1>');
} else if (req.url === '/api' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'API response' }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
HTTP Methods
const server = http.createServer((req, res) => {
switch (req.method) {
case 'GET': // Read
case 'POST': // Create
case 'PUT': // Update
case 'DELETE': // Delete
}
});
Reading Request Body
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.end('Received');
});
HTTPS Server
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, handler).listen(443);
Mini Practice
- Create a basic HTTP server
- Handle different routes
- Read request body
- Set response headers
Up Next
Continue with HTTPS — secure HTTP servers.
Related Topics
Frequently Asked Questions about HTTP
What is HTTP in Node.js?
HTTP is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn HTTP?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn HTTP.
Why is HTTP important in Node.js?
HTTP is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.