Master Express.js fundamentals with our comprehensive tutorial. Learn through examples and hands-on practice.
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
A basic Express.js server setup
Routing refers to determining how your application responds to client requests to particular endpoints (URIs).
const express = require('express');
const app = express();
// Handle GET request
app.get('/users', (req, res) => {
res.json([{ name: 'John' }, { name: 'Jane' }]);
});
// Handle POST request
app.post('/users', (req, res) => {
// Create new user
res.status(201).send('User created');
});
// Route parameters
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Different types of route handlers in Express.js
Middleware functions are functions that have access to the request object, response object, and the next middleware function in the application's request-response cycle.
const express = require('express');
const app = express();
// Custom middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
// Use middleware
app.use(logger);
// Built-in middleware
app.use(express.json());
app.use(express.static('public'));
app.post('/api/data', (req, res) => {
console.log(req.body); // Parsed JSON data
res.json({ received: true });
});
Using built-in and custom middleware in Express.js