Express.js is a minimal and flexible Node.js web application framework that simplifies building server-side applications and APIs.
- Middleware-based: Uses middleware functions to handle requests, responses, and add features like authentication, logging, or error handling.
- Routing system: structure—developers can design apps as they want.
- Integration: Works well with databases (MongoDB, MySQL, PostgreSQL) and front-end frameworks.
- Scalable: Suitable for small apps to large-scale enterprise APIs.
"Hello World" Example
Let's create a simple "Hello World" application with Express.
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello, Geeks!');
});
app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});
For Express.js installation, follow: Installing Express.js
Start the Server:
Run your server with the following command
node server.js
Web Browser Output
When you navigate to http://localhost:3000 in your web browser, you should see:
How Express.js Works?
Express.js works by handling client requests through a series of steps called the request-response cycle, using middleware and routing to process requests and send responses efficiently.
- A client sends a request (e.g., browser or app) to the Express server.
- The request passes through middleware functions that can modify the request, perform logging, authentication, or other tasks.
- Express matches the request to a route handler based on the URL and HTTP method.
- The route handler processes the request and prepares a response.
- The server sends the response back to the client.
- If any error occurs, it is caught by error-handling middleware to ensure the server remains stable.
Basic Routing in Express.js
Basic routing in Express.js is the process of defining URL endpoints (routes) and specifying how the server should respond to client requests at those endpoints.
Express provides simple methods to define routes that correspond to HTTP methods:
app.get() - Handle GET requestsapp.post() - Handle POST requestsapp.put() - Handle PUT requestsapp.delete() - Handle DELETE requestsapp.all() - Handle all HTTP methods
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// Basic Routing Examples
// Handle GET requests
app.get('/get-example', (req, res) => {
res.send('This is a GET request');
});
// Handle POST requests
app.post('/post-example', (req, res) => {
res.send('This is a POST request');
});
// Handle PUT requests
app.put('/put-example', (req, res) => {
res.send('This is a PUT request');
});
// Handle DELETE requests
app.delete('/delete-example', (req, res) => {
res.send('This is a DELETE request');
});
// Handle all HTTP methods
app.all('/all-example', (req, res) => {
res.send(`This handles all HTTP methods: ${req.method}`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
To understand Routing in detail, refer to article: Routing
Parameters in Express.js
Parameters in Express.js are values that are passed in the URL or request that your server can use to process the request dynamically. They allow your routes to handle different inputs without creating multiple static routes.
Types of Parameters in Express:
1. Route Parameters: Part of the URL (e.g., /users/:id) accessed via req.params.
Example:
JavaScript
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
2. Query Parameters: Appended to the URL (e.g., /search?term=nodejs) accessed via req.query.
JavaScript
app.get('/search', (req, res) => {
const searchTerm = req.query.term;
res.send(`Searching for ${searchTerm}`);
});
3. Request Body Parameters: Sent in POST or PUT requests, accessed via req.body with express.json() middleware.
JavaScript
app.use(express.json());
app.post('/users', (req, res) => {
const { name, age } = req.body;
res.send(`User created: ${name}, Age: ${age}`);
});
To understand Parameters in detail, refer to article: Parameters
Middleware in Express.js
Middleware in Express.js is a function that executes during the request-response cycle. It has access to the request (req) and response (res) objects, and can either end the request-response process or pass control to the next middleware using next().
Middleware is used for
- Logging requests
- Authentication and authorization
- Parsing request bodies
- Handling errors
Built-in Middleware
Express includes several useful middleware functions:
express.json() - Parse JSON request bodiesexpress.urlencoded() - Parse URL-encoded request bodiesexpress.static() - Serve static filesexpress.Router() - Create modular route handlers
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to log requests
app.use((req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next(); // Pass control to the next middleware/route
});
// Middleware to parse JSON bodies
app.use(express.json());
// Route handler
app.get('/', (req, res) => {
res.send('Hello, Express with middleware!');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
To understand Middleware detail, refer to article: Middleware
Error Handling in Express.js
Error handling in Express is done through special middleware functions that have four arguments:
(err, req, res, next).
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to simulate an error
app.get('/error', (req, res, next) => {
const err = new Error('Something went wrong!');
err.status = 500;
next(err); // Pass error to error-handling middleware
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error
res.status(err.status || 500).send({
message: err.message,
status: err.status || 500
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
To understand Error handling in Express detail, refer to article: Error handling
Where to Use Express.JS?
Express.js is a popular web framework for Node.js that simplifies server-side development. It is widely used to build web applications, APIs, and scalable server-side solutions.
- Web Applications: Express.js is ideal for building dynamic websites and single-page applications (SPAs) that require fast and efficient server-side handling.
- RESTful APIs: It’s widely used to create APIs that handle CRUD operations, serving data to front-end applications or mobile apps.
- Middleware-based Applications: Express allows integration of middleware for logging, authentication, input validation, and other request processing tasks.
- Microservices: Its lightweight and modular design makes it suitable for developing microservices in a scalable architecture.
- Server-side Rendering: Works seamlessly with template engines like EJS, Pug, or Handlebars to render HTML pages on the server.
- Proxy and Gateway Servers: Can act as a proxy or gateway, routing requests to different services and managing HTTP traffic efficiently.
- Rapid Prototyping: Developers often use Express for quickly setting up server-side logic and testing ideas before scaling applications.
Explore
HTML & CSS Tutorials
JS Tutorial
Frontend
Backend
Database