Kursinhalt
Backend-Entwicklung mit Node.js und Express.js
Backend-Entwicklung mit Node.js und Express.js
Implementierung der Route "Post Nach ID Aktualisieren"
Wir werden untersuchen, wie man einen bestehenden Beitrag mit der Route "UPDATE POST BY ID" innerhalb der Datei postsRoutes.js
aktualisiert. Diese Route behandelt die Aktualisierung eines Beitrags basierend auf seiner eindeutigen ID.
Routendefinition
Der folgende Code definiert die Route "UPDATE POST BY ID" mit router.put()
:
router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
- Diese Route ist konfiguriert, um HTTP PUT-Anfragen zu bearbeiten, speziell für die Aktualisierung von Beiträgen;
- Sie enthält einen parametrisierten
:id
im Routenpfad, um den zu aktualisierenden Beitrag zu identifizieren; - Das
validatePostData
Middleware wird hinzugefügt, um die Datenvalidierung vor dem Fortfahren sicherzustellen. Die Logik desvalidatePostData
Middleware bleibt gleich wie im vorherigen Schritt.
Daten aus der Anfrage erhalten
Hier extrahieren wir die notwendigen Daten aus der Anfrage, einschließlich der Post-ID und des aktualisierten Post-Inhalts:
const postId = req.params.id;
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
- Die Post-ID wird aus den Anfrageparametern extrahiert und steht für die weitere Verarbeitung zur Verfügung. Der
:id
-Parameter aus der Routen-URL wird mitreq.params.id
erfasst; - Der
username
,postTitle
undpostContent
werden aus dem Anfragekörper extrahiert.
Aktualisieren des Posts in der Datenbank
Das Aktualisieren eines bestehenden Posts umfasst mehrere Schritte, wie unten beschrieben:
const data = await readData();
const postIndex = data.findIndex((post) => post.id === postId);
if (postIndex === -1) {
return res.status(404).json({ error: "Post not found" });
}
data[postIndex] = {
...data[postIndex],
...updatedData,
};
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Wir lesen die vorhandenen Daten aus der JSON-Datei mit der asynchronen
readData
-Funktion, wie zuvor erklärt; - Die Variable
postIndex
speichert den Index des zu aktualisierenden Posts imdata
-Array, indem Post-IDs verglichen werden; - Wenn der Post nicht gefunden wird (d.h.
postIndex === -1
), wird eine 404 (Nicht gefunden) Antwort mit einer Fehlermeldung an den Client zurückgegeben; - Um die Post-Daten zu aktualisieren, kombinieren wir die vorhandenen Post-Daten (
...data[postIndex]
) mit den aktualisierten Daten (...updatedData
). Dies stellt sicher, dass nur die angegebenen Felder aktualisiert werden und vorhandene Daten erhalten bleiben; - Schließlich wird das aktualisierte
data
-Array zurück in die JSON-Datei geschrieben, um die vorgenommenen Änderungen am Post zu speichern.
Senden einer Antwort
Nach erfolgreicher Aktualisierung des Posts wird eine JSON-Antwort an den Client gesendet. Die Antwort enthält einen Statuscode von 200 (OK), der eine erfolgreiche Aktualisierung und die aktualisierten Post-Daten anzeigt.
res.status(200).json(data[postIndex]);
Fehlerbehandlung
Wir umschließen den Routencode in einem Try-Catch-Block, um potenzielle Fehler bei der Datenabfrage oder der Anforderungsverarbeitung zu behandeln. Alle auftretenden Fehler werden zur Debugging-Zwecken in der Konsole protokolliert:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Vollständiger Code der Datei postsRoutes.js in diesem Schritt
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);
}
});
// CREATE POST
router.post("/", validatePostData, async (req, res, next) => {
try {
const newPost = {
id: Date.now().toString(), // Generate a unique ID for the new post
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
// Read the existing data
const data = await readData();
// Add the new post to the data
data.push(newPost);
// Write the updated data back to the JSON file
await fs.writeFile("./database/posts.json", JSON.stringify(data));
// Send a success response with the new post
res.status(201).json(newPost);
} catch (error) {
// Handle errors by logging them to the console
console.error(error.message);
}
});
// UPDATE POST BY ID
router.put("/post/:id", validatePostData, async (req, res, next) => {
try {
// Extract the post ID from the request parameters
const postId = req.params.id;
// Extract the updated data from the request body
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
// Read the existing data
const data = await readData();
// Find the index of the post with the specified ID in the data array
const postIndex = data.findIndex((post) => post.id === postId);
// If the post with the specified ID doesn't exist, return a 404 error
if (postIndex === -1) {
return res.status(404).json({ error: "Post not found" });
}
// Update the post data with the new data using spread syntax
data[postIndex] = {
...data[postIndex], // Keep existing data
...updatedData, // Apply updated data
};
// Write the updated data back
await fs.writeFile("./database/posts.json", JSON.stringify(data));
// Send a success response with the updated post
res.status(200).json(data[postIndex]);
} catch (error) {
console.error(error.message);
next(error);
}
});
Danke für Ihr Feedback!