Introducción a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas dinámicas
Body parser
Postman
CRUD
¿Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Solución del reto de validación
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticación utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creación y Migración de Modelos con Prisma para Citas Médicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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:
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.
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:
/users/:id
where :id
is a dynamic parameter.req.params.id
When accessing a URL such as /users/123
, our application will capture "123" as the value of userId
and respond appropriately.
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:
/search
route that captures query parameters.req.query.
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.
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:
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
Want to see more contributions, questions and answers from the community?