Express makes working with Node.js HTTP easier by adding helpful tools and simpler ways to handle web requests and responses.
0
0
How Express builds on Node.js HTTP
Introduction
You want to create a web server that handles different web pages or API calls.
You need to manage routes (URLs) easily without writing lots of code.
You want to handle user input and send back responses quickly.
You want to add middleware to process requests step-by-step.
You want to build a web app without dealing with low-level HTTP details.
Syntax
Express
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World'); }); app.listen(3000);
Express uses the Node.js HTTP module under the hood but hides its complexity.
app.get() defines a route for GET requests, making routing simple.
Examples
Defines a simple GET route for the home page that sends a welcome message.
Express
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Welcome to Home Page'); });
Handles POST requests to '/submit' URL, useful for form data.
Express
const express = require('express'); const app = express(); app.post('/submit', (req, res) => { res.send('Form submitted'); });
Middleware example that logs every request before moving to next handler.
Express
const express = require('express'); const app = express(); app.use((req, res, next) => { console.log('Request received'); next(); });
Sample Program
This program creates an Express server that logs every request and responds with a message on the home page.
Express
const express = require('express'); const app = express(); // Middleware to log requests app.use((req, res, next) => { console.log(`Received ${req.method} request for ${req.url}`); next(); }); // Route for home page app.get('/', (req, res) => { res.send('Hello from Express!'); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Express simplifies routing compared to raw Node.js HTTP module.
Middleware functions in Express let you process requests step-by-step.
Express still uses Node.js HTTP server internally, so it is fast and efficient.
Summary
Express builds on Node.js HTTP by adding easy routing and middleware support.
It hides complex HTTP details so you can focus on your app logic.
Express helps you write less code to handle web requests and responses.