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

bookCreazione dell'Endpoint GET Post per ID

Esamineremo l'implementazione della rotta "GET POST BY ID" all'interno del file postsRoutes.js file. Questa rotta recupera e restituisce un post specifico in base al suo identificatore univoco (id) fornito come parte dell'URL.

Nota

Il termine 'database' si riferisce specificamente al file posts.json situato nella cartella database.

Definizione della Rotta

Il codice seguente definisce la rotta "GET POST BY ID" utilizzando router.get():

router.get("/post/:id", async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire richieste HTTP GET;
  • Il percorso della rotta /post/:id include un parametro :id, che acquisisce l'ID del post dall'URL.

Estrazione dell'ID del Post

L'ID del post viene estratto dai parametri della richiesta utilizzando req.params.id:

const postId = req.params.id;

Questa riga acquisisce il valore :id dall'URL, rendendolo disponibile per l'elaborazione successiva.

Ricerca del Post nel Database

Successivamente, si ricerca il post con l'ID corrispondente nel database:

const data = await readData();

const post = data.find((post) => post.id === postId);
  • Si utilizza la funzione asincrona readData per recuperare i dati dal file JSON;
  • Il metodo find() viene impiegato per individuare un post con ID corrispondente all'interno dei dati recuperati;
  • La variabile post contiene il post trovato oppure undefined se non viene trovata alcuna corrispondenza.

Gestione della risposta

La risposta viene gestita in base al fatto che un post sia stato trovato o meno:

if (!post) {
  res.status(404).json({ error: "Post not found" });
} else {
  res.status(200).send(post);
}
  • Se nessun post viene trovato (cioè, post è undefined), viene inviata una risposta 404 insieme a un messaggio di errore, indicando che il post richiesto non è stato trovato;
  • Se un post viene trovato, il post viene inviato come risposta con codice di stato 200 (OK).

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire eventuali errori durante il recupero dei dati o l'elaborazione della richiesta. Qualsiasi errore che si verifica viene registrato nella console per scopi di debug:

try {
  // ... (code for retrieving and processing data)
} catch (error) {
  console.error(error.message);
}

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
  }
});

// GET POST BY ID
router.get("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;
    // Read data from the JSON file
    const data = await readData();

    // Find the post with the matching ID
    const post = data.find((post) => post.id === postId);

    // If the post is not found, send a 404 response
    if (!post) {
      res.status(404).json({ error: "Post not found" });
    } else {
      // If the post is found, send it as the response
      res.status(200).send(post);
    }
  } catch (error) {
    // Handle errors by logging them and sending an error response
    console.error(error.message);
  }
});

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 6

Chieda ad AI

expand

Chieda ad AI

ChatGPT

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

Suggested prompts:

Can you explain how the readData function works in more detail?

What should I do if I get an error when trying to fetch a post by ID?

How can I test this GET POST BY ID route using a tool like Postman?

Awesome!

Completion rate improved to 2.56

bookCreazione dell'Endpoint GET Post per ID

Scorri per mostrare il menu

Esamineremo l'implementazione della rotta "GET POST BY ID" all'interno del file postsRoutes.js file. Questa rotta recupera e restituisce un post specifico in base al suo identificatore univoco (id) fornito come parte dell'URL.

Nota

Il termine 'database' si riferisce specificamente al file posts.json situato nella cartella database.

Definizione della Rotta

Il codice seguente definisce la rotta "GET POST BY ID" utilizzando router.get():

router.get("/post/:id", async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire richieste HTTP GET;
  • Il percorso della rotta /post/:id include un parametro :id, che acquisisce l'ID del post dall'URL.

Estrazione dell'ID del Post

L'ID del post viene estratto dai parametri della richiesta utilizzando req.params.id:

const postId = req.params.id;

Questa riga acquisisce il valore :id dall'URL, rendendolo disponibile per l'elaborazione successiva.

Ricerca del Post nel Database

Successivamente, si ricerca il post con l'ID corrispondente nel database:

const data = await readData();

const post = data.find((post) => post.id === postId);
  • Si utilizza la funzione asincrona readData per recuperare i dati dal file JSON;
  • Il metodo find() viene impiegato per individuare un post con ID corrispondente all'interno dei dati recuperati;
  • La variabile post contiene il post trovato oppure undefined se non viene trovata alcuna corrispondenza.

Gestione della risposta

La risposta viene gestita in base al fatto che un post sia stato trovato o meno:

if (!post) {
  res.status(404).json({ error: "Post not found" });
} else {
  res.status(200).send(post);
}
  • Se nessun post viene trovato (cioè, post è undefined), viene inviata una risposta 404 insieme a un messaggio di errore, indicando che il post richiesto non è stato trovato;
  • Se un post viene trovato, il post viene inviato come risposta con codice di stato 200 (OK).

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire eventuali errori durante il recupero dei dati o l'elaborazione della richiesta. Qualsiasi errore che si verifica viene registrato nella console per scopi di debug:

try {
  // ... (code for retrieving and processing data)
} catch (error) {
  console.error(error.message);
}

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
  }
});

// GET POST BY ID
router.get("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;
    // Read data from the JSON file
    const data = await readData();

    // Find the post with the matching ID
    const post = data.find((post) => post.id === postId);

    // If the post is not found, send a 404 response
    if (!post) {
      res.status(404).json({ error: "Post not found" });
    } else {
      // If the post is found, send it as the response
      res.status(200).send(post);
    }
  } catch (error) {
    // Handle errors by logging them and sending an error response
    console.error(error.message);
  }
});

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 6
some-alt