Het Bouwen van het CREATE-Post Eindpunt
We onderzoeken het aanmaken van een nieuw bericht via de "CREATE POST"-route in het bestand postsRoutes.js. Deze route is verantwoordelijk voor het verwerken van het aanmaken van een bericht en het opslaan ervan in de gegevensbron (database/posts.json).
Routedefinitie
De onderstaande code definieert de "CREATE POST"-route met behulp van router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Deze route is geconfigureerd om HTTP POST-verzoeken naar het rootpad
/af te handelen; - Er wordt gebruikgemaakt van de middleware
validatePostData, die ervoor zorgt dat de gegevens in de request body geldig zijn voordat er verder wordt gegaan.
Middleware voor Gegevensvalidatie
Voordat we ingaan op de logica van de route, moeten we een middleware voor gegevensvalidatie maken. Deze middleware zorgt ervoor dat de gegevens die in de request body worden verzonden geldig zijn voordat er wordt geprobeerd een nieuw bericht aan te maken.
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
- De functie
validatePostDatahaaltusername,postTitleenpostContentuit de request body; - Er wordt gecontroleerd of deze velden aanwezig zijn. Als een van deze ontbreekt (
!username,!postTitleof!postContent), wordt er gereageerd met een 400 (Bad Request) statuscode en een foutmelding die aangeeft dat verplichte velden ontbreken; - Als de gegevens geldig zijn, roept de middleware
next()aan, waardoor het verzoek wordt doorgegeven aan de route handler (in dit geval de "CREATE POST"-route).
Met de gegevensvalidatie-middleware op zijn plaats, gaan we verder met de logica van de "CREATE POST"-route.
Nieuwe Postgegevens
Om een nieuw bericht aan te maken, genereren we een unieke ID met behulp van Date.now().toString(). Daarnaast halen we de username, postTitle en postContent uit de request body.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Voeg de Nieuwe Post toe aan de Database
De volgende stappen beschrijven hoe het nieuwe bericht aan de database wordt toegevoegd:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- De bestaande gegevens worden uit het JSON-bestand gelezen met behulp van de asynchrone functie
readData, zoals eerder uitgelegd; - Het nieuwe bericht wordt toegevoegd aan de
dataarray; - De bijgewerkte
dataarray wordt vervolgens teruggeschreven naar het JSON-bestand om het nieuw aangemaakte bericht op te slaan.
Verzenden van een response
Na succesvolle aanmaak van het nieuwe bericht wordt een succesrespons naar de client gestuurd. De response bevat een statuscode van 201 (Aangemaakt) en de details van het nieuw aangemaakte bericht in JSON-formaat.
res.status(201).json(newPost);
Foutafhandeling
We plaatsen de routecode in een try-catch-blok om mogelijke fouten tijdens het ophalen van gegevens of het verwerken van het verzoek af te handelen. Eventuele fouten die optreden worden gelogd naar de console voor debugdoeleinden:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Volledige code van het postsRoutes.js-bestand in deze stap
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 {
// Generate a unique ID for the new post
const newPost = {
id: Date.now().toString(),
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);
}
});
Volledige code van het validateData.js-bestand
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
module.exports = validatePostData;
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Awesome!
Completion rate improved to 2.56
Het Bouwen van het CREATE-Post Eindpunt
Veeg om het menu te tonen
We onderzoeken het aanmaken van een nieuw bericht via de "CREATE POST"-route in het bestand postsRoutes.js. Deze route is verantwoordelijk voor het verwerken van het aanmaken van een bericht en het opslaan ervan in de gegevensbron (database/posts.json).
Routedefinitie
De onderstaande code definieert de "CREATE POST"-route met behulp van router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Deze route is geconfigureerd om HTTP POST-verzoeken naar het rootpad
/af te handelen; - Er wordt gebruikgemaakt van de middleware
validatePostData, die ervoor zorgt dat de gegevens in de request body geldig zijn voordat er verder wordt gegaan.
Middleware voor Gegevensvalidatie
Voordat we ingaan op de logica van de route, moeten we een middleware voor gegevensvalidatie maken. Deze middleware zorgt ervoor dat de gegevens die in de request body worden verzonden geldig zijn voordat er wordt geprobeerd een nieuw bericht aan te maken.
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
- De functie
validatePostDatahaaltusername,postTitleenpostContentuit de request body; - Er wordt gecontroleerd of deze velden aanwezig zijn. Als een van deze ontbreekt (
!username,!postTitleof!postContent), wordt er gereageerd met een 400 (Bad Request) statuscode en een foutmelding die aangeeft dat verplichte velden ontbreken; - Als de gegevens geldig zijn, roept de middleware
next()aan, waardoor het verzoek wordt doorgegeven aan de route handler (in dit geval de "CREATE POST"-route).
Met de gegevensvalidatie-middleware op zijn plaats, gaan we verder met de logica van de "CREATE POST"-route.
Nieuwe Postgegevens
Om een nieuw bericht aan te maken, genereren we een unieke ID met behulp van Date.now().toString(). Daarnaast halen we de username, postTitle en postContent uit de request body.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Voeg de Nieuwe Post toe aan de Database
De volgende stappen beschrijven hoe het nieuwe bericht aan de database wordt toegevoegd:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- De bestaande gegevens worden uit het JSON-bestand gelezen met behulp van de asynchrone functie
readData, zoals eerder uitgelegd; - Het nieuwe bericht wordt toegevoegd aan de
dataarray; - De bijgewerkte
dataarray wordt vervolgens teruggeschreven naar het JSON-bestand om het nieuw aangemaakte bericht op te slaan.
Verzenden van een response
Na succesvolle aanmaak van het nieuwe bericht wordt een succesrespons naar de client gestuurd. De response bevat een statuscode van 201 (Aangemaakt) en de details van het nieuw aangemaakte bericht in JSON-formaat.
res.status(201).json(newPost);
Foutafhandeling
We plaatsen de routecode in een try-catch-blok om mogelijke fouten tijdens het ophalen van gegevens of het verwerken van het verzoek af te handelen. Eventuele fouten die optreden worden gelogd naar de console voor debugdoeleinden:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Volledige code van het postsRoutes.js-bestand in deze stap
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 {
// Generate a unique ID for the new post
const newPost = {
id: Date.now().toString(),
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);
}
});
Volledige code van het validateData.js-bestand
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
module.exports = validatePostData;
Bedankt voor je feedback!