Creazione 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.jsonsituato nella cartelladatabase.
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/:idinclude 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
readDataper 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
postcontiene il post trovato oppureundefinedse 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);
}
});
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
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
Creazione 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.jsonsituato nella cartelladatabase.
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/:idinclude 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
readDataper 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
postcontiene il post trovato oppureundefinedse 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);
}
});
Grazie per i tuoi commenti!