Express.js routes play a crucial role in determining how your application responds to different URLs. In this post, we’ll explore the world of Express.js routes and learn how to navigate your web application with ease.
Express.js routes are path that defines how your application responds to a specific URL. It’s essentially a mapping between a URL and a handler function that determines what happens when that URL is accessed. Routes can be defined using various HTTP methods, such as GET, POST, PUT, and DELETE.
There are several types of routes in Express.js, including:
const express = require('express');
const app = express();
To define a route in Express.js, you use the app.METHOD()
function, where METHOD
is the HTTP method you want to use (e.g., app.get()
, app.post()
, etc.). For example:
app.get('/', (req, res) => {
res.send('GET Request to / Route');
});
app.post('/', (req, res) => {
res.send('POST Request to / Route');
});
This defines a static route that responds to GET requests to the root URL (/
) with the message “Hello World!”.
Express.js provides various methods to handle different HTTP request methods. Here’s a breakdown of the most commonly used ones:
app.get('/users', (req, res) => {
// Retrieve users from a database
res.json(users);
});
app.post('/users', (req, res) => {
// Create a new user based on the request body
const newUser = req.body;
// Save the user to the database
res.status(201).json(newUser);
});
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedUser = req.body;
// Update the user with the given ID
res.json(updatedUser);
});
app.patch('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedFields = req.body;
// Update only the specified fields of the user
res.json(updatedUser);
});
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
// Delete the user with the given ID
res.sendStatus(204);
});
app.head('/users', (req, res) => {
// Send a HEAD response with appropriate headers
res.sendStatus(200);
});
app.options('/users', (req, res) => {
res.header('Allow', 'GET, POST, PUT, PATCH, DELETE');
res.sendStatus(200);
});
While less commonly used, Express also supports other HTTP methods like:
TRACE
CONNECT
COPY
MOVE
PROPFIND
PROPPATCH
MKCOL
LOCK
UNLOCK
Route parameters allow you to capture values from the URL and pass them to your handler function.
:
) to define dynamic parts of the path.req.params
object.app.get('/users/:id', (req, res) => {
const id = req.params.id;
res.send(`User ${id} found!`);
});
This defines a dynamic route that allows to handle requests for user information when user visits a URL like `/users/124
` where 124 is User Id that can be any value.
// Middleware for /users route.
app.use('/users', (req, res, next) => {
// Authentication logic
next();
});
// /users route.
app.get('/users/:id', (req, res) => {
// User data
res.send("User data");
});
app.use()
.app.use()
with four arguments.app.METHOD(path, middleware, callback)
syntax.app.use()
with four arguments (req, res, next, err) to catch and handle errors that occur within your routes.app.use()
with a path parameter. This can simplify route definitions and improve organization.app.METHOD(path, middleware, callback)
syntax.app.use()
with four arguments (req, res, next, err) to catch and handle errors that occur within your routes.app.use()
with a path parameter. This can simplify route definitions and improve organization.By understanding how to define static and dynamic routes, use route parameters, and create nested routes, you’ll be well on your way to building robust and scalable web applications. In next post we will explore the express.js middlewares.
You can learn more on official site of Express.js.
Want to run node.js on Android? Read how to install node.js in Termux.