The Express Framework
Express is a minimal, fast, and unopinionated web framework for Node.js. It acts as a wrapper around the native http module, providing robust tools for API routing, parameter parsing, and middleware integration.
Installation
npm install express
Basic Routing Structure
Express allows you to separate specific URL endpoints into distinct block configurations.
import express from 'express';
const app = express();
const PORT = 3000;
// Respond to standard GET requests
app.get('/', (req, res) => {
res.send('Welcome to the Homepage');
});
// Returning a formatted JSON payload
app.get('/api/status', (req, res) => {
res.json({ status: "Healthy", uptime: "99.9%" });
});
app.listen(PORT, () => {
console.log(`Express listening on Port ${PORT}`);
});
Middleware
Middleware functions execute directly in the middle of the request-response cycle. They have access to the incoming req object and can modify it before the final route handler executes.
Common middleware uses include parsing incoming JSON bodies, logging request data, or verifying authentication tokens.
// Adding a global middleware that parses incoming JSON bodies
app.use(express.json());
// A custom logging middleware
const logger = (req, res, next) => {
console.log(`${req.method} request received at ${req.url}`);
// The 'next()' call pushes the request to the next block in the chain
next();
};
app.use(logger);
// Extracting POST data (parsed by the express.json middleware)
app.post('/login', (req, res) => {
const username = req.body.username;
if (username === "admin") {
res.send("Access Granted.");
} else {
res.send("Access Denied.");
}
});