Node.js has become a dominant platform for building backend services, and Express.js is its most popular web framework. Together, they provide a fast and efficient way to create RESTful APIs, which are the backbone of many modern web and mobile applications.
What is Express.js?
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies tasks like routing, handling requests and responses, and managing middleware.
Setting Up a Basic Express Server
First, ensure you have Node.js and npm (or yarn) installed. Initialize your project and install Express:
npm init -y
npm install express
Now, create a basic server file (e.g., server.js
):
const express = require('express');
const app = express();
const port = process.env.PORT || 3000; // Use environment variable or default
// Middleware to parse JSON bodies
app.use(express.json());
// Basic route for the homepage
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Start the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
Run this file using node server.js
.
Understanding Routing
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, PUT, DELETE, etc.).
Express provides methods to define routes:
// GET request to /api/users
app.get('/api/users', (req, res) => {
// Logic to fetch users from a database
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
res.json(users); // Send JSON response
});
// POST request to /api/users
app.post('/api/users', (req, res) => {
// Logic to create a new user based on req.body
const newUser = req.body;
console.log('Creating user:', newUser);
// Assume user creation is successful
res.status(201).json({ id: 3, ...newUser }); // Send 201 Created status
});
// GET request with a route parameter
app.get('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id, 10); // Access the 'id' parameter
// Logic to find user by ID
const user = { id: userId, name: `User ${userId}` }; // Dummy data
if (user) {
res.json(user);
} else {
res.status(404).send('User not found');
}
});
Middleware
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. They can execute code, make changes to the request and response objects, end the request-response cycle, or call the next middleware.
Examples include logging, authentication, data validation, and parsing request bodies (like express.json()
used earlier).
// Simple logger middleware
const requestLogger = (req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next(); // Pass control to the next middleware/route handler
};
// Apply middleware globally
app.use(requestLogger);
// Apply middleware to specific routes
const authMiddleware = (req, res, next) => {
// Dummy authentication check
if (req.headers['authorization'] === 'Bearer mysecrettoken') {
next();
} else {
res.status(401).send('Unauthorized');
}
};
app.get('/api/secure-data', authMiddleware, (req, res) => {
res.json({ data: 'This is protected data' });
});
Conclusion
Node.js and Express provide a powerful combination for building efficient and scalable RESTful APIs. By understanding core concepts like routing and middleware, you can structure your backend services effectively. This foundation allows you to build complex applications, integrate with databases, and create robust APIs for your frontend applications.