Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
HTTP Module
Before using frameworks like Express, it's important to understand how Node.js handles web requests using its built-in http module.
1. Creating a Basic Server
The createServer method takes a callback function that runs every time a request hits your server.
const http = require('http');
const server = http.createServer((req, res) => {
// req = Request (what comes in)
// res = Response (what goes out)
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello from the Server!');
});
const PORT = 5000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});2. Handling Routes
With the native HTTP module, you have to manually check the req.url.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.write('<h1>Welcome to Home Page</h1>');
res.end();
} else if (req.url === '/about') {
res.end('<h1>About Us</h1>');
} else {
res.statusCode = 404;
res.end('<h1>Page Not Found</h1>');
}
});
server.listen(5000);3. Responding with JSON
For APIs, you'll often need to send JSON data instead of HTML.
const server = http.createServer((req, res) => {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(users));
});Note: While the HTTP module is powerful, it becomes messy as your app grows. This is exactly why we use Express.js.