Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Creating and Managing Routes in Express.js | Developing Web Applications with Express.js
Backend Development with Node.js and Express.js

bookCreating and Managing Routes in Express.js

Let's explore these practical examples of creating routes in Express.js in more detail.

🌟 Basic Routes

Let's create a simple Express.js application with routes for different HTTP methods. Each route handles a specific HTTP request and sends a response back to the client.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('This is the homepage.');
});

app.post('/users', (req, res) => {
  // Handle user creation logic here.
  res.send('User created.');
});

app.put('/users/:id', (req, res) => {
  // Handle user update logic here.
  res.send(`User ${req.params.id} updated.`);
});

app.delete('/users/:id', (req, res) => {
  // Handle user deletion logic here.
  res.send(`User ${req.params.id} deleted.`);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000.');
});
  • GET Route: This route responds to a GET request at the root URL (/). Users who access the application's homepage will receive the message "This is the homepage.";
  • POST Route: This route responds to a POST request at the /users URL. It's typically used for creating new user records. The route includes a comment for handling user creation logic, which can be replaced with the actual user creation logic;
  • PUT Route: This route responds to a PUT request at the /users/:id URL. It's designed for updating user records based on the :id parameter. Like the POST route, it includes a comment handling user update logic;
  • DELETE Route: This route responds to a DELETE request at the /users/:id URL. It's used for deleting user records based on the :id parameter. As with the other routes, it includes a comment for handling user deletion logic.

Note

If you're uncertain about the URL or would like to review the concept, please refer to the following article: URL vs URI vs URN

🌟 Handle URL Parameters

Let's focus on creating a route that handles URL parameters. URL parameters are dynamic parts of a URL that can be used to pass data to the server. Here's how this example works:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Fetch user data based on `userId`.
  res.send(`User details for ID ${userId}.`);
});
  • We define a route using app.get('/users/:id', ...), where :id is a URL parameter. This means that when a user accesses a URL like /users/123, the req.params.id variable will contain the value 123;
  • Inside the route handler, we access the :id parameter using req.params.id;
  • You can replace the comment with logic to fetch user data based on the userId obtained from the URL parameter;
  • Finally, we respond to the client with information about the user identified by the :id parameter.

🌟 Route Order and Prioritization

The order in which routes are defined matters because Express uses a first-match-wins strategy. The first matching route will be executed. In this example, we consider a scenario where you have both a specific and a catch-all route:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Fetch user data based on `userId`.
  res.send(`User details for ID ${userId}.`);
});

app.get('/users/*', (req, res) => {
  // Handle generic user-related requests.
  res.send('User-related request.');
});
  • The first route, app.get('/users/:id', ...), is a specific route that responds to URLs like /users/123. It will handle requests with a specific user ID;
  • The second route, app.get('/users/*', ...), is a catch-all route for generic user-related requests. It uses a wildcard (*) to match any URL that starts with /users/, such as /users/settings.

In this scenario, the order is crucial. The specific route should be defined before the catch-all route to ensure it takes precedence. If you define the catch-all route first, it will match all URLs starting with /users/, and the specific route won't have a chance to handle requests with a user ID.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 5

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 2.56

bookCreating and Managing Routes in Express.js

Deslize para mostrar o menu

Let's explore these practical examples of creating routes in Express.js in more detail.

🌟 Basic Routes

Let's create a simple Express.js application with routes for different HTTP methods. Each route handles a specific HTTP request and sends a response back to the client.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('This is the homepage.');
});

app.post('/users', (req, res) => {
  // Handle user creation logic here.
  res.send('User created.');
});

app.put('/users/:id', (req, res) => {
  // Handle user update logic here.
  res.send(`User ${req.params.id} updated.`);
});

app.delete('/users/:id', (req, res) => {
  // Handle user deletion logic here.
  res.send(`User ${req.params.id} deleted.`);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000.');
});
  • GET Route: This route responds to a GET request at the root URL (/). Users who access the application's homepage will receive the message "This is the homepage.";
  • POST Route: This route responds to a POST request at the /users URL. It's typically used for creating new user records. The route includes a comment for handling user creation logic, which can be replaced with the actual user creation logic;
  • PUT Route: This route responds to a PUT request at the /users/:id URL. It's designed for updating user records based on the :id parameter. Like the POST route, it includes a comment handling user update logic;
  • DELETE Route: This route responds to a DELETE request at the /users/:id URL. It's used for deleting user records based on the :id parameter. As with the other routes, it includes a comment for handling user deletion logic.

Note

If you're uncertain about the URL or would like to review the concept, please refer to the following article: URL vs URI vs URN

🌟 Handle URL Parameters

Let's focus on creating a route that handles URL parameters. URL parameters are dynamic parts of a URL that can be used to pass data to the server. Here's how this example works:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Fetch user data based on `userId`.
  res.send(`User details for ID ${userId}.`);
});
  • We define a route using app.get('/users/:id', ...), where :id is a URL parameter. This means that when a user accesses a URL like /users/123, the req.params.id variable will contain the value 123;
  • Inside the route handler, we access the :id parameter using req.params.id;
  • You can replace the comment with logic to fetch user data based on the userId obtained from the URL parameter;
  • Finally, we respond to the client with information about the user identified by the :id parameter.

🌟 Route Order and Prioritization

The order in which routes are defined matters because Express uses a first-match-wins strategy. The first matching route will be executed. In this example, we consider a scenario where you have both a specific and a catch-all route:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Fetch user data based on `userId`.
  res.send(`User details for ID ${userId}.`);
});

app.get('/users/*', (req, res) => {
  // Handle generic user-related requests.
  res.send('User-related request.');
});
  • The first route, app.get('/users/:id', ...), is a specific route that responds to URLs like /users/123. It will handle requests with a specific user ID;
  • The second route, app.get('/users/*', ...), is a catch-all route for generic user-related requests. It uses a wildcard (*) to match any URL that starts with /users/, such as /users/settings.

In this scenario, the order is crucial. The specific route should be defined before the catch-all route to ensure it takes precedence. If you define the catch-all route first, it will match all URLs starting with /users/, and the specific route won't have a chance to handle requests with a user ID.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 5
some-alt