This article focuses on essential things to know Express.js, a key part of building backend applications with Node.js. I'll dive into routing, CRUD operations, response methods, and middleware functions, all of which play a critical role in building robust web applications.
Concept Highlights:
- Route Methods and CRUD
- Routing Parameters
- Route Handlers
- Response Methods
- Built-in Middleware Functions
1. Route Methods and CRUD
In Express.js, route methods define how your application responds to different HTTP requests (e.g., GET, POST, PUT, DELETE) for specific routes. These methods are used to implement CRUD (Create, Read, Update, Delete) operations in your application.
Basic CRUD example: In this example, each route responds to a different CRUD operation based on the HTTP method used.
const express = require('express');
const app = express();
// Create - POST
app.post('/users', (req, res) => {
res.send('User created');
});
// Read - GET
app.get('/users', (req, res) => {
res.send('Here is the user');
});
// Update - PUT
app.put('/users/:id', (req, res) => {
res.send('User with ID ${req.params.id} updated');
});
// Delete - DELETE
app.delete('/users//:id', (req, res) => {
res.send('User with ID ${req.params.id} deleted');
}):
app.listen(3000, () =>
console.log('Server running on port 3000')
);
2. Routing Parameters
Routing parameters allow you to capture specific parts of the request URL and use them within your route handlers. For instance, you can extract an ID from the URL and use it to perform an action related to that ID.
e.g.) In this example, :id
is a dynamic parameter, which will be extracted and used in the response. If this dynamic parameter is 123
, a request to /users/123
will return "Fetching user with ID: 123."
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Fetching user with ID: ${userId}`);
});
3. Route Handlers
Route handlers define how your server handles HTTP requests. You can define multiple middleware functions within a single route, allowing for cleaner and modular code.
Example with multiple handlers: In this example, the first middleware logs a message, and the second middleware sends the response.
app.get('/users', (req, res, next) => {
console.log('First middleware');
next(); // call the next handler in the stack
}, (req, res) => {
res.send('User list');
});
4. Response Methods
Express.js provides several methods for sending responses to the client. Let's explore some commonly used response methods.
a) .json()
sends a JSON response.
app.get('/data', (req, res) => {
res.json({ message: 'Hello, JSON' });
});
b) .send()
sends a response of various types (text, HTML, buffer, etc.).
app.get('/text', (req, res) => {
res.send('Sending text');
});
c) .download()
sends a file as an attachment, prompting the user to download it.
app.get('/download', (req, res) => {
res.download('path/to/file.pdf');
});
d) .redirect()
redirects the client to a different URL.
app.get('/redirect', (req, res) => {
res.redirect('https://example.com');
});
5. Built-in Middleware Functions
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next
function. They are used for modifying the request or response objects, ending the request-response cycle, or calling the next middleware.
a) express.static
: this middleware serves static files (like images, CSS files, etc.) from a directory.
e.g.) In this example, any file in the public
directory can be accessed via the browser like localhost:3000/image.jpg
.
app.use(express.static('public'));
b) express.json
: this middleware parses incoming JSON payloads from the client.
e.g.) This is essential when handling POST or PUT requests with JSON data.
app.use(express.json());
c) express.urlencoded
: this middleware parses URL-encoded payloads (typically from form submissions).
e.g.) The extended: true
option allows for parsing nested objects.
app.use(express.urlencoded({ extended: true }));
Top comments (0)