Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Creazione dell'Endpoint GET per Tutti i Post | Creazione di API REST con Node.js ed Express.js
Sviluppo Backend con Node.js ed Express.js

Creazione dell'Endpoint GET per Tutti i Post

Scorri per mostrare il menu

Esplorazione dell'implementazione della rotta "GET ALL POSTS" nel file postsRoutes.js. Questa rotta recupera un elenco di tutti i post dalla fonte dati (database/posts.json) e li invia come risposta al client.

Importazione dei moduli e delle dipendenze necessari

All'inizio del file vengono importati i moduli e le dipendenze richiesti:

const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");
  • express: Importazione del framework Express per la creazione delle rotte;
  • fs/promises: Modulo che fornisce operazioni asincrone sui file, utilizzato per leggere i dati da un file JSON;
  • validatePostData: Anche se non utilizzato in questa rotta, viene importato il middleware validatePostData, utile per la validazione dei dati nei capitoli successivi.

Inizializzazione di un Router Express

Inizializzazione di un'istanza di router Express, responsabile della gestione di tutte le rotte definite in questo file:

const router = express.Router();

Creazione di una funzione per la lettura dei dati

Definizione di una funzione asincrona chiamata readData per leggere i dati da un file JSON. Questa funzione garantisce il corretto recupero dei dati e gestisce eventuali errori:

// Function to read data from the JSON file
async function readData() {
  try {
    // Read the contents of the `posts.json` file
    const data = await fs.readFile("./database/posts.json");
    // Parse the JSON data into a JavaScript object
    return JSON.parse(data);
  } catch (error) {
    // If an error occurs during reading or parsing, throw the error
    throw error;
  }
}
  • fs.readFile: Utilizzo di fs.readFile per leggere il contenuto del file ./database/posts.json;
  • JSON.parse: I dati recuperati dal file vengono convertiti in un oggetto JavaScript;
  • Gestione degli errori: Eventuali errori durante la lettura o la conversione vengono intercettati e lanciati.

Definizione della rotta "GET ALL POSTS"

Definizione della rotta "GET ALL POSTS" all'interno del router:

// GET ALL POSTS
router.get("/", async (req, res, next) => {
  try {
    // Call the `readData` function to retrieve the list of posts
    const data = await readData();
    // Send the retrieved data as the response
    res.status(200).send(data);
  } catch (error) {
    // If an error occurs during data retrieval or sending the response
    console.error(error.message); // Log the error to the console for debugging
  }
});

Definizione della rotta: Specifica che questa rotta gestisce le richieste HTTP GET al percorso root (/).

Gestore della rotta: All'interno della funzione handler della rotta:

  • Chiamata della funzione readData per recuperare l'elenco dei post dal file JSON;
  • In caso di successo, invio dei dati recuperati come risposta tramite res.send(data);
  • In caso di errore durante il processo, intercettazione dell'errore, registrazione nel console per il debug (console.error(error.message)) e prosecuzione.

Codice completo del file postsRoutes.js a questo passaggio

const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");

const router = express.Router();

// Function to read data from the JSON file
async function readData() {
  try {
    // Read the contents of the `posts.json` file
    const data = await fs.readFile("./database/posts.json");
    // Parse the JSON data into a JavaScript object
    return JSON.parse(data);
  } catch (error) {
    // If an error occurs during reading or parsing, throw the error
    throw error;
  }
}

// GET ALL POSTS
router.get("/", async (req, res, next) => {
  try {
    // Call the `readData` function to retrieve the list of posts
    const data = await readData();
    // Send the retrieved data as the response
    res.status(200).send(data);
  } catch (error) {
    // If an error occurs during data retrieval or sending the response
    console.error(error.message); // Log the error to the console for debugging
  }
});

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 5

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 4. Capitolo 5
some-alt