Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Erstellung des DELETE-Endpunkts für Beiträge nach ID | Erstellung von REST-APIs mit Node.js und Express.js
Backend-Entwicklung mit Node.js und Express.js

bookErstellung des DELETE-Endpunkts für Beiträge nach ID

Wir beschäftigen uns mit der Implementierung der Route "DELETE POST BY ID" in der Datei postsRoutes.js. Diese Route ermöglicht es Clients, einen bestimmten Beitrag durch Angabe seiner eindeutigen ID zu löschen.

Routendefinition

Der folgende Code definiert die Route "DELETE POST BY ID" mit router.delete():

router.delete("/post/:id", async (req, res, next) => { ... }

Diese Route verarbeitet HTTP DELETE-Anfragen mit einem parametrisierten :id im Routenpfad. Der Parameter :id dient zur Identifizierung des zu löschenden Beitrags. Zusätzliche Middleware wie dataValidation ist nicht erforderlich, da alle notwendigen Informationen über den URL-Parameter bereitgestellt werden.

Extrahieren der Post-ID

Die Post-ID wird aus den Request-Parametern mit req.params.id extrahiert:

const postId = req.params.id;

Diese Zeile liest den Wert von :id aus der URL aus, sodass wir im weiteren Code damit arbeiten können.

Beitrag löschen

So wird der Beitrag gelöscht:

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.splice(postIndex, 1);

await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • Zunächst werden die vorhandenen Daten mit der asynchronen Funktion readData aus der JSON-Datei gelesen, wie zuvor erläutert.
  • Der Index des zu löschenden Beitrags wird im Array data durch den Vergleich der Beitrags-IDs ermittelt.
  • Wird der Beitrag nicht gefunden (d. h. postIndex === -1), erfolgt eine 404-Fehlermeldung (Nicht gefunden) mit einer Fehlermeldung.
  • Mit der Methode splice wird der Beitrag aus dem Array data entfernt. Die Variable postIndex bestimmt die Position des zu löschenden Beitrags.
  • Das aktualisierte Array data, aus dem der Beitrag entfernt wurde, wird anschließend wieder in die JSON-Datei geschrieben, um die Änderungen zu speichern.

Senden einer Antwort

Eine JSON-Antwort mit dem Statuscode 200 (OK) wird an den Client gesendet, um eine erfolgreiche Löschung anzuzeigen. Die Antwort enthält eine Nachricht, die bestätigt, dass der Beitrag erfolgreich gelöscht wurde:

res.status(200).json({ message: "Post deleted successfully" });

Fehlerbehandlung

Der Routencode wird in einen try-catch-Block eingebettet, um potenzielle Fehler beim Datenabruf oder bei der Verarbeitung der Anfrage zu behandeln. Auftretende Fehler werden zur Fehlersuche 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);
  }
});

// DELETE POST BY ID
router.delete("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;

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

    // Remove the post from the data array using `splice`
    data.splice(postIndex, 1);

    // Write the updated data back to the data source (e.g., a JSON file)
    await fs.writeFile("./database/posts.json", JSON.stringify(data));

    // Send a success response with the JSON response indicating successful deletion
    res.status(200).json({ message: "Post deleted successfully" });
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

module.exports = router;

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 9

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Suggested prompts:

Can you explain how the error handling works in the DELETE route?

What would happen if the post ID provided does not exist?

Can you summarize the main steps involved in deleting a post?

Awesome!

Completion rate improved to 2.56

bookErstellung des DELETE-Endpunkts für Beiträge nach ID

Swipe um das Menü anzuzeigen

Wir beschäftigen uns mit der Implementierung der Route "DELETE POST BY ID" in der Datei postsRoutes.js. Diese Route ermöglicht es Clients, einen bestimmten Beitrag durch Angabe seiner eindeutigen ID zu löschen.

Routendefinition

Der folgende Code definiert die Route "DELETE POST BY ID" mit router.delete():

router.delete("/post/:id", async (req, res, next) => { ... }

Diese Route verarbeitet HTTP DELETE-Anfragen mit einem parametrisierten :id im Routenpfad. Der Parameter :id dient zur Identifizierung des zu löschenden Beitrags. Zusätzliche Middleware wie dataValidation ist nicht erforderlich, da alle notwendigen Informationen über den URL-Parameter bereitgestellt werden.

Extrahieren der Post-ID

Die Post-ID wird aus den Request-Parametern mit req.params.id extrahiert:

const postId = req.params.id;

Diese Zeile liest den Wert von :id aus der URL aus, sodass wir im weiteren Code damit arbeiten können.

Beitrag löschen

So wird der Beitrag gelöscht:

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.splice(postIndex, 1);

await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • Zunächst werden die vorhandenen Daten mit der asynchronen Funktion readData aus der JSON-Datei gelesen, wie zuvor erläutert.
  • Der Index des zu löschenden Beitrags wird im Array data durch den Vergleich der Beitrags-IDs ermittelt.
  • Wird der Beitrag nicht gefunden (d. h. postIndex === -1), erfolgt eine 404-Fehlermeldung (Nicht gefunden) mit einer Fehlermeldung.
  • Mit der Methode splice wird der Beitrag aus dem Array data entfernt. Die Variable postIndex bestimmt die Position des zu löschenden Beitrags.
  • Das aktualisierte Array data, aus dem der Beitrag entfernt wurde, wird anschließend wieder in die JSON-Datei geschrieben, um die Änderungen zu speichern.

Senden einer Antwort

Eine JSON-Antwort mit dem Statuscode 200 (OK) wird an den Client gesendet, um eine erfolgreiche Löschung anzuzeigen. Die Antwort enthält eine Nachricht, die bestätigt, dass der Beitrag erfolgreich gelöscht wurde:

res.status(200).json({ message: "Post deleted successfully" });

Fehlerbehandlung

Der Routencode wird in einen try-catch-Block eingebettet, um potenzielle Fehler beim Datenabruf oder bei der Verarbeitung der Anfrage zu behandeln. Auftretende Fehler werden zur Fehlersuche 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);
  }
});

// DELETE POST BY ID
router.delete("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;

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

    // Remove the post from the data array using `splice`
    data.splice(postIndex, 1);

    // Write the updated data back to the data source (e.g., a JSON file)
    await fs.writeFile("./database/posts.json", JSON.stringify(data));

    // Send a success response with the JSON response indicating successful deletion
    res.status(200).json({ message: "Post deleted successfully" });
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

module.exports = router;

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 9
some-alt