Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Building the GET Post by Id Endpoint | Building REST APIs with Node.js and Express.js
Backend Development with Node.js and Express.js

book
Building the GET Post by Id Endpoint

We will explore implementing the "GET POST BY ID" route within the postsRoutes.js file. This route fetches and returns a specific post based on its unique identifier (id) provided as part of the URL.

Note

The term 'database' specifically pertains to the posts.json file located in the database folder.

Route Definition

The code below defines the "GET POST BY ID" route using router.get():

js
router.get("/post/:id", async (req, res, next) => { ... }
  • This route is configured to handle HTTP GET requests;

  • The route path /post/:id includes a parameter :id , which captures the post ID from the URL.

Extracting the Post ID

We extract the post ID from the request parameters using req.params.id:

js
const postId = req.params.id;

This line captures the :id value from the URL, making it available for further processing.

Finding the Post in the Database

Next, we search for the post with the matching ID in the database:

js
const data = await readData();

const post = data.find((post) => post.id === postId);
  • We use the asynchronous readData function to retrieve data from the JSON file;

  • The find() method is employed to locate a post with a matching ID within the retrieved data;

  • The post variable holds the found post or undefined if no match is found.

Handling the Response

We handle the response based on whether a post was found or not:

js
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
res.status(200).send(post);
}
  • If no post was found (i.e., post is undefined ), we send a 404 response along with an error message, indicating that the requested post was not found;

  • If a post was found, we send the post as the response with a status code of 200 (OK).

Error Handling

We wrap the route code in a try-catch block to handle potential errors during data retrieval or request processing. Any errors that occur are logged to the console for debugging purposes:

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

Complete code of the postsRoutes.js file at this step

js
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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 6

Spørg AI

expand
ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt