You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
5 Hrs
50 Min
34 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Rutas dinámicas

4/30
Resources

Creating robust APIs with Express.js requires proper configuration to handle different types of requests and data. In this article, we will explore how to configure essential middleware such as body-parser to process incoming data, and how to implement dynamic routes and query parameters to create a flexible and functional API. These skills are fundamental for any developer looking to build modern web applications with Node.js.

How to configure body-parser to process data in Express?

Body-parser is essential middleware for any Express application that needs to process data sent in POST, PUT or DELETE requests. This middleware allows us to parse and transform the received data into usable formats within our application.

To get started, we need to install body-parser in our project:

npm install body-parser

Once installed, we need to incorporate it into our application:

const bodyParser = require('body-parser');

The basic configuration of body-parser includes two main aspects:

app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));

With these two lines, our application can now:

  • Process data in JSON format sent in the body of requests.
  • Handle URL-encoded data (such as those submitted from HTML forms).

This configuration is crucial when building APIs that will receive data in different formats, especially when working with POST requests containing JSON or form data.

How to implement dynamic routes in Express?

Dynamic routes allow us to capture specific values provided by the user in the URL. This is particularly useful when we need to identify specific resources, such as users, products or any entity with a unique identifier.

To create a dynamic route, we use the colon symbol (:) followed by the parameter name:

app.get('/users/:id', (req, res) => { const userId = req.params.id; res.send(`Showuser information with ID: ${userId}`);});

In this example:

  • We define a path /users/:id where :id is a dynamic parameter.
  • We capture the value of this parameter with req.params.id
  • We reply with a message that includes the provided ID

When accessing a URL such as /users/123, our application will capture "123" as the value of userId and respond appropriately.

How to work with query parameters in Express?

Query parameters are another way to receive data from the user, especially useful for implementing search, filtering and paging functionality in our APIs.

To implement a route that handles query parameters:

app.get('/search', (req, res) => { const terms = req.query.term || "not specified"; const category = req.query.category || "all";  
 res.send(`<h2>Search results</h2> <p>Term: ${terms}</p> <p>Category: ${category}</p>`);});});

In this example:

  • We create a /search route that captures query parameters.
  • We access these parameters through req.query.
  • We provide default values in case certain parameters are not specified.

To use this path, we could access a URL like:/search?term=express%20js&category=node.js

The application will extract the values "express js" for the term and "node.js" for the category, and display them in the response.

How to structure a complete API with Express?

When building an API with Express, it is important to maintain an organized structure that facilitates maintenance and scalability. A good practice is to group related routes and separate the business logic from the route controllers.

For a complete API, we will need to implement different HTTP methods:

  • GET to get information
  • POST to create new resources
  • PUT/PATCH to update existing resources
  • DELETE to delete resources

Each of these methods may require different ways of processing the incoming data, which makes the body-parser configuration essential.

The basic structure for each type of route could be:

// GET route with dynamic parametersapp.get('/resources/:id', (req, res) => { // Logic to get a specific resource});
// POST route to create resourcesapp.post('/resources', (req, res) => { // Access data sent in the request body const newResource = req.body; // Logic to create the resource});
// PUT route to update resourcesapp.put('/resources/:id', (req, res) => { const id = req.params.id; const updatedData = req.body; // Logic to update the resource});
// DELETE path to delete resourcesapp.delete('/resources/:id', (req, res) => { const id = req.params.id; // Logic to delete the resource});

Implementing these concepts will allow you to create robust and flexible APIs that can handle different types of requests and data efficiently.

Properly configuring middleware such as body-parser and implementing dynamic routes and query parameters are fundamental skills for any Express developer. Practice creating different types of routes and processing different data formats to strengthen your understanding of these concepts. What other aspects of Express would you like to explore in your application? Share your experiences in the comments.

Contributions 2

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

A partir de **Express v4.16.0**, ya no es necesario instalar el paquete `body-parser` para manejar JSON o formularios (`urlencoded`). Express ya incluye internamente los métodos `express.json()` y `express.urlencoded()` que cumplen la misma función. Esto simplifica el código y reduce dependencias externas. Solo usa `body-parser` si necesitas algo muy específico. **Ejemplo moderno recomendado:** `app.use(express.json`()); `app.use(express.urlencoded({ extended: true }));`
El método `express.urlencoded()` de Express se utiliza para parsear los datos de formularios enviados con el método POST. Permite que tu aplicación pueda interpretar datos en formato `application/x-www-form-urlencoded`, que es el formato estándar utilizado por los navegadores al enviar formularios. Al usar `app.use(express.urlencoded({ extended: true }))`, se habilita la posibilidad de acceder a los datos del formulario a través de `req.body`, facilitando su manipulación en tu aplicación. Esto es crucial para gestionar datos de usuarios, como en registros o inicios de sesión.