Learn Express.js framework for building robust web applications and REST APIs with Node.js.
Learn Express.js framework for building robust web applications and REST APIs with Node.js.
Set up Express.js applications and understand the basic structure and configuration
Content by: Sachin Patel
Node.js Developer
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building web applications and APIs by providing a clean, simple API for handling HTTP requests and responses.
// Install Express.js
npm install express
// Basic Express.js server
const express = require('express');
const app = express();
const port = 3000;
// Middleware for parsing JSON
app.use(express.json());
// Middleware for parsing URL-encoded bodies
app.use(express.urlencoded({ extended: true }));
// Basic route
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Start server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
// Express.js with ES modules
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Test your understanding of this topic:
Learn Express.js routing patterns and middleware implementation for request processing
Content by: Parth Patel
Node.js Developer
Routing refers to determining how an application responds to a client request to a particular endpoint. Express.js provides a robust routing system that allows you to define routes for different HTTP methods and URL patterns.
const express = require('express');
const app = express();
// GET route
app.get('/users', (req, res) => {
res.json({ message: 'Get all users' });
});
// POST route
app.post('/users', (req, res) => {
res.json({ message: 'Create new user', data: req.body });
});
// PUT route
app.put('/users/:id', (req, res) => {
res.json({ message: 'Update user', id: req.params.id });
});
// DELETE route
app.delete('/users/:id', (req, res) => {
res.json({ message: 'Delete user', id: req.params.id });
});
// Route with parameters
app.get('/users/:id', (req, res) => {
res.json({ message: 'Get user by ID', id: req.params.id });
});
// Route with query parameters
app.get('/search', (req, res) => {
const { q, page } = req.query;
res.json({ message: 'Search results', query: q, page: page });
});
// Multiple route handlers
app.get('/users/:id',
(req, res, next) => {
console.log('Middleware 1');
next();
},
(req, res, next) => {
console.log('Middleware 2');
next();
},
(req, res) => {
res.json({ message: 'Get user', id: req.params.id });
}
);
const express = require('express');
const app = express();
// Application-level middleware
app.use((req, res, next) => {
console.log('Request URL:', req.url);
console.log('Request Method:', req.method);
console.log('Timestamp:', new Date().toISOString());
next();
});
// Middleware for specific routes
app.use('/api', (req, res, next) => {
console.log('API request');
next();
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// Custom middleware function
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
// Verify token logic here
req.user = { id: 1, name: 'John Doe' };
next();
};
// Using custom middleware
app.get('/protected', authMiddleware, (req, res) => {
res.json({ message: 'Protected route', user: req.user });
});
// Middleware for parsing JSON
app.use(express.json());
// Middleware for serving static files
app.use(express.static('public'));
// CORS middleware
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
next();
});
Test your understanding of this topic:
Master request and response handling in Express.js applications
Content by: Bansi Patel
Node.js Developer
The request object (req) contains information about the HTTP request that triggered the route handler. It includes properties like headers, body, parameters, and query strings.
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Accessing request properties
app.get('/example', (req, res) => {
// URL and path
console.log('URL:', req.url);
console.log('Path:', req.path);
console.log('Base URL:', req.baseUrl);
// HTTP method
console.log('Method:', req.method);
// Headers
console.log('Headers:', req.headers);
console.log('User Agent:', req.get('User-Agent'));
// Query parameters
console.log('Query:', req.query);
console.log('Search:', req.query.search);
// Route parameters
console.log('Params:', req.params);
// Request body (for POST, PUT, PATCH)
console.log('Body:', req.body);
// IP address
console.log('IP:', req.ip);
// Hostname
console.log('Hostname:', req.hostname);
res.json({ message: 'Request details logged' });
});
// Handling different content types
app.post('/users', (req, res) => {
const { name, email, age } = req.body;
// Validate required fields
if (!name || !email) {
return res.status(400).json({ error: 'Name and email are required' });
}
// Process the data
const user = { name, email, age: age || null };
res.status(201).json({ message: 'User created', user });
});
// File upload handling
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
res.json({
message: 'File uploaded successfully',
filename: req.file.filename,
originalname: req.file.originalname,
size: req.file.size
});
});
const express = require('express');
const app = express();
// Sending different response types
app.get('/responses', (req, res) => {
// JSON response
res.json({ message: 'JSON response' });
// HTML response
res.send('<h1>HTML response</h1>');
// Plain text response
res.send('Plain text response');
// Redirect
res.redirect('/new-page');
// Send file
res.sendFile('/path/to/file.html');
// Download file
res.download('/path/to/file.pdf');
});
// Setting response headers
app.get('/headers', (req, res) => {
res.set('Content-Type', 'application/json');
res.set('X-Custom-Header', 'Custom Value');
res.status(200).json({ message: 'Headers set' });
});
// Different HTTP status codes
app.get('/status', (req, res) => {
// Success responses
res.status(200).json({ message: 'OK' });
res.status(201).json({ message: 'Created' });
// Client error responses
res.status(400).json({ error: 'Bad Request' });
res.status(401).json({ error: 'Unauthorized' });
res.status(404).json({ error: 'Not Found' });
// Server error responses
res.status(500).json({ error: 'Internal Server Error' });
res.status(503).json({ error: 'Service Unavailable' });
});
// Streaming responses
app.get('/stream', (req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Transfer-Encoding', 'chunked');
let counter = 0;
const interval = setInterval(() => {
res.write(`Data chunk ${counter}\n`);
counter++;
if (counter >= 10) {
clearInterval(interval);
res.end('Stream complete');
}
}, 1000);
});
// Error responses
app.get('/error', (req, res) => {
try {
// Simulate an error
throw new Error('Something went wrong');
} catch (error) {
res.status(500).json({
error: 'Internal Server Error',
message: error.message
});
}
});
Test your understanding of this topic:
Implement proper error handling and validation in Express.js applications
Content by: Noman Mansuri
Node.js Developer
Error handling is crucial for building robust Express.js applications. Express.js provides built-in error handling mechanisms and allows you to create custom error handlers for different scenarios.
const express = require('express');
const app = express();
// Error handling middleware (must be last)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// Async error handling
app.get('/async', async (req, res, next) => {
try {
const result = await someAsyncOperation();
res.json(result);
} catch (error) {
next(error); // Pass error to error handling middleware
}
});
// Express 5.0+ async error handling
app.get('/async-v5', async (req, res) => {
const result = await someAsyncOperation();
res.json(result);
// Errors are automatically caught and passed to error middleware
});
// Custom error class
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
// Using custom error class
app.get('/users/:id', (req, res, next) => {
const userId = req.params.id;
if (!userId || isNaN(userId)) {
return next(new AppError('Invalid user ID', 400));
}
// Process user logic
res.json({ message: 'User found', id: userId });
});
// Error handling middleware for custom errors
app.use((err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
if (process.env.NODE_ENV === 'development') {
res.status(err.statusCode).json({
status: err.status,
error: err,
message: err.message,
stack: err.stack
});
} else {
// Production error response
if (err.isOperational) {
res.status(err.statusCode).json({
status: err.status,
message: err.message
});
} else {
// Programming or unknown errors
console.error('ERROR 💥', err);
res.status(500).json({
status: 'error',
message: 'Something went wrong!'
});
}
}
});
const express = require('express');
const app = express();
app.use(express.json());
// Manual validation
app.post('/users', (req, res, next) => {
const { name, email, age } = req.body;
// Validation
if (!name || name.trim().length < 2) {
return res.status(400).json({ error: 'Name must be at least 2 characters long' });
}
if (!email || !email.includes('@')) {
return res.status(400).json({ error: 'Valid email is required' });
}
if (age && (age < 0 || age > 120)) {
return res.status(400).json({ error: 'Age must be between 0 and 120' });
}
// Process valid data
res.status(201).json({ message: 'User created successfully' });
});
// Using validation libraries
const { body, validationResult } = require('express-validator');
app.post('/users-validated', [
body('name').isLength({ min: 2 }).withMessage('Name must be at least 2 characters'),
body('email').isEmail().withMessage('Must be a valid email'),
body('age').optional().isInt({ min: 0, max: 120 }).withMessage('Age must be between 0 and 120')
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.status(201).json({ message: 'User created successfully' });
});
// Sanitization
const { body, sanitizeBody } = require('express-validator');
app.post('/users-sanitized', [
body('name').trim().escape(),
body('email').normalizeEmail(),
sanitizeBody('age').toInt()
], (req, res) => {
// Data is now sanitized
res.status(201).json({ message: 'User created', data: req.body });
});
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 3