Bygga GET-endpunkten för Post efter ID
Vi kommer att undersöka implementeringen av "GET POST BY ID"-rutten i filen postsRoutes.js file. Denna rutt hämtar och returnerar ett specifikt inlägg baserat på dess unika identifierare (id) som anges som en del av URL:en.
Obs
Termen 'database' avser specifikt filen
posts.jsonsom finns i mappendatabase.
Routedefinition
Koden nedan definierar "GET POST BY ID"-routen med hjälp av router.get():
router.get("/post/:id", async (req, res, next) => { ... }
- Denna route är konfigurerad för att hantera HTTP GET-förfrågningar;
- Ruttvägen
/post/:idinnehåller en parameter:id, som fångar upp postens ID från URL:en.
Extrahera post-ID
Vi extraherar postens ID från förfrågningsparametrarna med req.params.id:
const postId = req.params.id;
Denna rad fångar värdet för :id från URL:en och gör det tillgängligt för vidare bearbetning.
Hitta posten i databasen
Därefter söker vi efter posten med motsvarande ID i databasen:
const data = await readData();
const post = data.find((post) => post.id === postId);
- Vi använder den asynkrona funktionen
readDataför att hämta data från JSON-filen; - Metoden
find()används för att lokalisera en post med motsvarande ID i den hämtade datan; - Variabeln
postinnehåller den hittade posten ellerundefinedom ingen matchning hittas.
Hantering av svaret
Svaret hanteras beroende på om ett inlägg hittades eller inte:
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
res.status(200).send(post);
}
- Om inget inlägg hittades (dvs.
postärundefined), skickas ett 404-svar tillsammans med ett felmeddelande som indikerar att det begärda inlägget inte hittades; - Om ett inlägg hittades skickas inlägget som svar med statuskod 200 (OK).
Felhantering
Vi kapslar in ruttkoden i ett try-catch-block för att hantera potentiella fel vid datahämtning eller begäran. Alla fel som uppstår loggas till konsolen för felsökning:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Komplett kod för postsRoutes.js-filen i detta steg
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);
}
});
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
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
Bygga GET-endpunkten för Post efter ID
Svep för att visa menyn
Vi kommer att undersöka implementeringen av "GET POST BY ID"-rutten i filen postsRoutes.js file. Denna rutt hämtar och returnerar ett specifikt inlägg baserat på dess unika identifierare (id) som anges som en del av URL:en.
Obs
Termen 'database' avser specifikt filen
posts.jsonsom finns i mappendatabase.
Routedefinition
Koden nedan definierar "GET POST BY ID"-routen med hjälp av router.get():
router.get("/post/:id", async (req, res, next) => { ... }
- Denna route är konfigurerad för att hantera HTTP GET-förfrågningar;
- Ruttvägen
/post/:idinnehåller en parameter:id, som fångar upp postens ID från URL:en.
Extrahera post-ID
Vi extraherar postens ID från förfrågningsparametrarna med req.params.id:
const postId = req.params.id;
Denna rad fångar värdet för :id från URL:en och gör det tillgängligt för vidare bearbetning.
Hitta posten i databasen
Därefter söker vi efter posten med motsvarande ID i databasen:
const data = await readData();
const post = data.find((post) => post.id === postId);
- Vi använder den asynkrona funktionen
readDataför att hämta data från JSON-filen; - Metoden
find()används för att lokalisera en post med motsvarande ID i den hämtade datan; - Variabeln
postinnehåller den hittade posten ellerundefinedom ingen matchning hittas.
Hantering av svaret
Svaret hanteras beroende på om ett inlägg hittades eller inte:
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
res.status(200).send(post);
}
- Om inget inlägg hittades (dvs.
postärundefined), skickas ett 404-svar tillsammans med ett felmeddelande som indikerar att det begärda inlägget inte hittades; - Om ett inlägg hittades skickas inlägget som svar med statuskod 200 (OK).
Felhantering
Vi kapslar in ruttkoden i ett try-catch-block för att hantera potentiella fel vid datahämtning eller begäran. Alla fel som uppstår loggas till konsolen för felsökning:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Komplett kod för postsRoutes.js-filen i detta steg
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);
}
});
Tack för dina kommentarer!