Introduction
Transitioning from a basic HTTP server to an Express server is like upgrading from a manual typewriter to a modern word processor. While both accomplish the core task, Express streamlines and enhances the experience with built-in tools and conveniences.
Starting with an HTTP Server
Here is a basic HTTP server:
const http = require('http');
const server = http.createServer((req, res) => {
let reqBody = "";
req.on("data", (data) => {
reqBody += data;
});
req.on("end", () => {
if (reqBody) {
req.body = JSON.parse(reqBody);
}
if (req.method === 'GET' && req.url.startsWith('/users/')) {
const urlParts = req.url.split('/');
if (urlParts.length === 3) {
const userId = urlParts[2];
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.write('User details for userId: ');
res.write(userId);
return res.end();
}
}
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.write('Not Found');
return res.end();
});
});
const port = 5000;
server.listen(port, () => console.log('Server is listening on port', port));
This server handles requests manually, parsing the URL and body while implementing one route.
Converting to Express
Using Express simplifies and enhances the server logic:
const express = require('express');
const app = express();
// Parse JSON bodies
app.use(express.json());
// Define routes
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.status(200).send(`User details for userId: ${userId}`);
});
// Start the server
const port = 5000;
app.listen(port, () => console.log('Server is listening on port', port));
Key Differences
1. Route Handling
In HTTP:
if (req.method === 'GET' && req.url.startsWith('/users/')) {
const urlParts = req.url.split('/');
const userId = urlParts[2];
}
In Express:
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
});
Express simplifies route creation and parameter extraction.
2. Body Parsing
In HTTP:
let reqBody = "";
req.on("data", (data) => {
reqBody += data;
});
req.on("end", () => {
req.body = JSON.parse(reqBody);
});
In Express:
app.use(express.json());
Express automatically parses JSON request bodies.
3. Response Handling
In HTTP:
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.write('Response Text');
res.end();
In Express:
res.status(200).send('Response Text');
Express methods combine status setting, headers, and content in one step.
Why Choose Express?
Express is the logical choice for modern web applications due to its:
- Readability: Less boilerplate code compared to HTTP servers.
- Built-in Features: Middleware for body parsing, routing, and more.
- Flexibility: Supports RESTful API design, making it ideal for microservices.
- Community Support: A vast ecosystem of plugins and resources.
Real-World Example
Consider a blogging platform:
GET /posts: Retrieve all blog posts.POST /posts: Create a new post.GET /posts/:id: Retrieve a post by ID.PUT /posts/:id: Update a post by ID.DELETE /posts/:id: Delete a post by ID.
Using Express, these routes are easy to define and maintain.