Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Implementing the "UPDATE POST BY ID" Route | Developing REST API
Backend Development with Node.js and Express.js
course content

Зміст курсу

Backend Development with Node.js and Express.js

Backend Development with Node.js and Express.js

1. Introduction
2. Console Applications
3. Express.js Framework
4. Developing REST API

bookImplementing the "UPDATE POST BY ID" Route

We will research how to update an existing post using the "UPDATE POST BY ID" route within the postsRoutes.js file. This route handles the updating of a post based on its unique ID.

Route Definition

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

  • This route is configured to handle HTTP PUT requests, specifically for updating posts;
  • It includes a parameterized :id in the route path to identify the post to be updated;
  • The validatePostData middleware is added to ensure data validation before proceeding. The logic of the validatePostData middleware remains the same as in the previous step.

Obtaining Data from the Request

Here, we extract the necessary data from the request, including the post ID and the updated post content:

  • The post ID is extracted from the request parameters, making it available for further processing. The :id parameter from the route URL is captured using req.params.id;
  • The username, postTitle, and postContent are extracted from the request body.

Update the Post in the Database

Updating an existing post involves several steps, as outlined below:

  • We read the existing data from the JSON file using the asynchronous readData function, as explained earlier;
  • The postIndex variable stores the index of the post to be updated in the data array by comparing post IDs;
  • If the post is not found (i.e., postIndex === -1), a 404 (Not Found) response with an error message is returned to the client;
  • To update the post data, we merge the existing post data (...data[postIndex]) with the updated data (...updatedData). This ensures that only the specified fields are updated and existing data is retained;
  • Finally, the updated data array is written back to the JSON file to save the changes made to the post.

Sending a Response

Upon successful post update, a JSON response is sent to the client. The response includes a status code of 200 (OK), indicating a successful update and the updated post data.

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:

Complete code of the postsRoutes.js file at this step

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 8
some-alt