Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Get-Postauksen Hakeminen Tunnisteen Perusteella | REST-rajapintojen Rakentaminen Node.js:llä ja Express.js:llä
Backend-kehitys Node.js:llä ja Express.js:llä

Get-Postauksen Hakeminen Tunnisteen Perusteella

Pyyhkäise näyttääksesi valikon

Tässä tarkastellaan "GET POST BY ID" -reitin toteutusta tiedostossa postsRoutes.js file. Tämä reitti hakee ja palauttaa tietyn postauksen sen yksilöllisen tunnisteen (id) perusteella, joka annetaan osana URL-osoitetta.

Note
Huomio

Termi 'database' viittaa nimenomaan posts.json -tiedostoon, joka sijaitsee database-kansiossa.

Reitin määrittely

Alla oleva koodi määrittelee "GET POST BY ID" -reitin käyttäen router.get()-metodia:

router.get("/post/:id", async (req, res, next) => { ... }
  • Tämä reitti on määritelty käsittelemään HTTP GET -pyyntöjä;
  • Reitin polku /post/:id sisältää parametrin :id, joka poimii postauksen tunnisteen URL-osoitteesta.

Postauksen ID:n poimiminen

Postauksen ID poimitaan pyynnön parametreista käyttämällä req.params.id:

const postId = req.params.id;

Tämä rivi tallentaa URL-osoitteesta saadun :id-arvon, jolloin se on käytettävissä jatkokäsittelyä varten.

Postauksen etsiminen tietokannasta

Seuraavaksi etsitään tietokannasta postaus, jonka ID vastaa annettua arvoa:

const data = await readData();

const post = data.find((post) => post.id === postId);
  • Asynkronista readData-funktiota käytetään tietojen hakemiseen JSON-tiedostosta;
  • find()-metodia käytetään postauksen etsimiseen haetuista tiedoista vastaavan ID:n perusteella;
  • post-muuttujaan tallentuu löydetty postaus tai undefined, jos vastaavaa postausta ei löydy.

Vastauksen käsittely

Vastaus käsitellään sen mukaan, löytyikö postaus vai ei:

if (!post) {
  res.status(404).json({ error: "Post not found" });
} else {
  res.status(200).send(post);
}
  • Jos postausta ei löydy (post on undefined), lähetetään 404-vastaus ja virheilmoitus, joka kertoo pyydetyn postauksen puuttumisesta;
  • Jos postaus löytyy, lähetetään postaus vastauksena tilakoodilla 200 (OK).

Virheenkäsittely

Reittikoodin ympärille asetetaan try-catch-lohko mahdollisten virheiden käsittelemiseksi tiedon haun tai pyynnön käsittelyn aikana. Kaikki esiintyvät virheet kirjataan konsoliin vianmääritystä varten:

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

postsRoutes.js-tiedoston täydellinen koodi tässä vaiheessa

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);
  }
});
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 4. Luku 6

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 4. Luku 6
some-alt