Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Implementing the "GET ALL POSTS" Route | Developing REST API
Node.js Express: API & CLI Apps
course content

Contenido del Curso

Node.js Express: API & CLI Apps

Node.js Express: API & CLI Apps

1. Introduction
2. Console Applications
3. Express.js Framework
4. Developing REST API

bookImplementing the "GET ALL POSTS" Route

We'll explore how to implement the "GET ALL POSTS" route in the postsRoutes.js file. This route retrieves a list of all posts from the data source (database/posts.json) and sends them as a response to the client.

Importing Required Modules and Dependencies

At the beginning of the file, we import the necessary modules and dependencies:

  • express: We import the Express framework for building our routes;
  • fs/promises: This module provides asynchronous file operations, which we'll use to read data from a JSON file;
  • validatePostData: Although not used in this route, we import the validatePostData middleware, which will be helpful for data validation in later chapters.

Initializing an Express Router

We initialize an instance of an Express router, which will handle all routes defined within this file:

Creating a Function to Read Data

We define an asynchronous function named readData to read data from a JSON file. This function ensures that data is retrieved properly and handles errors:

  • fs.readFile: We use fs.readFile to read the contents of the ./database/posts.json file;
  • JSON.parse: The data retrieved from the file is parsed into a JavaScript object;
  • Error Handling: If any errors occur during the reading or parsing process, they are caught, and the error is thrown.

Defining the "GET ALL POSTS" Route

Here's how we define the "GET ALL POSTS" route within the router:

Route Definition: We specify that this route handles HTTP GET requests to the root path (/).

Route Handler: Inside the route handler function:

  • We call the readData function to retrieve the list of posts from the JSON file;
  • If the data retrieval is successful, we send the retrieved data as the response using res.send(data);
  • If any errors occur during this process, we catch the error, log it to the console for debugging (console.error(error.message)), and continue.

Complete code of the postsRoutes.js file at this step

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 5
some-alt