Bygga Create-Poständpunkten
Vi kommer att undersöka hur man skapar ett nytt inlägg med hjälp av "CREATE POST"-rutten i filen postsRoutes.js. Denna rutt ansvarar för att hantera skapandet av ett inlägg och spara det till datakällan (database/posts.json).
Ruttdefinition
Koden nedan definierar "CREATE POST"-rutten med hjälp av router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Denna rutt är konfigurerad för att hantera HTTP POST-förfrågningar till rotvägen
/; - Den använder mellanprogrammet
validatePostData, vilket säkerställer att datan som skickas i förfrågans kropp är giltig innan processen fortsätter.
Datavaliderings-mellanprogram
Innan vi går in på routens logik måste vi skapa ett datavaliderings-mellanprogram. Detta mellanprogram säkerställer att datan som skickas i request body är giltig innan vi försöker skapa ett nytt inlägg.
// 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();
}
- Funktionen
validatePostDataextraherarusername,postTitleochpostContentfrån request body; - Den kontrollerar om dessa fält finns. Om något av dem saknas (
!username,!postTitleeller!postContent), svarar den med statuskod 400 (Bad Request) och ett felmeddelande som indikerar att obligatoriska fält saknas; - Om datan är giltig anropar mellanprogrammet
next(), vilket tillåter förfrågan att fortsätta till route handlern ("CREATE POST"-routen i detta fall).
Med datavaliderings-mellanprogrammet på plats kan vi fortsätta med logiken för "CREATE POST"-routen.
Ny inläggsdata
För att skapa ett nytt inlägg genererar vi ett unikt ID med hjälp av Date.now().toString(). Dessutom extraherar vi username, postTitle och postContent från request body.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Lägg till det nya inlägget i databasen
Följande steg beskriver hur det nya inlägget läggs till i databasen:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Befintlig data läses från JSON-filen med den asynkrona funktionen
readData, som tidigare förklarats; - Det nya inlägget läggs till i arrayen
data; - Den uppdaterade arrayen
dataskrivs sedan tillbaka till JSON-filen för att spara det nyskapade inlägget.
Skicka ett svar
Vid lyckad skapelse av det nya inlägget skickas ett svarsmeddelande till klienten. Svaret inkluderar statuskoden 201 (Created) och detaljer om det nyskapade inlägget i JSON-format.
res.status(201).json(newPost);
Felhantering
Vi omsluter rutkoden i ett try-catch-block för att hantera potentiella fel under datahämtning eller begäranshantering. Alla fel som uppstår loggas till konsolen för felsökningsändamål:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
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);
}
});
Komplett kod för validateData.js-filen
// 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;
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 2.56
Bygga Create-Poständpunkten
Svep för att visa menyn
Vi kommer att undersöka hur man skapar ett nytt inlägg med hjälp av "CREATE POST"-rutten i filen postsRoutes.js. Denna rutt ansvarar för att hantera skapandet av ett inlägg och spara det till datakällan (database/posts.json).
Ruttdefinition
Koden nedan definierar "CREATE POST"-rutten med hjälp av router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Denna rutt är konfigurerad för att hantera HTTP POST-förfrågningar till rotvägen
/; - Den använder mellanprogrammet
validatePostData, vilket säkerställer att datan som skickas i förfrågans kropp är giltig innan processen fortsätter.
Datavaliderings-mellanprogram
Innan vi går in på routens logik måste vi skapa ett datavaliderings-mellanprogram. Detta mellanprogram säkerställer att datan som skickas i request body är giltig innan vi försöker skapa ett nytt inlägg.
// 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();
}
- Funktionen
validatePostDataextraherarusername,postTitleochpostContentfrån request body; - Den kontrollerar om dessa fält finns. Om något av dem saknas (
!username,!postTitleeller!postContent), svarar den med statuskod 400 (Bad Request) och ett felmeddelande som indikerar att obligatoriska fält saknas; - Om datan är giltig anropar mellanprogrammet
next(), vilket tillåter förfrågan att fortsätta till route handlern ("CREATE POST"-routen i detta fall).
Med datavaliderings-mellanprogrammet på plats kan vi fortsätta med logiken för "CREATE POST"-routen.
Ny inläggsdata
För att skapa ett nytt inlägg genererar vi ett unikt ID med hjälp av Date.now().toString(). Dessutom extraherar vi username, postTitle och postContent från request body.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Lägg till det nya inlägget i databasen
Följande steg beskriver hur det nya inlägget läggs till i databasen:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Befintlig data läses från JSON-filen med den asynkrona funktionen
readData, som tidigare förklarats; - Det nya inlägget läggs till i arrayen
data; - Den uppdaterade arrayen
dataskrivs sedan tillbaka till JSON-filen för att spara det nyskapade inlägget.
Skicka ett svar
Vid lyckad skapelse av det nya inlägget skickas ett svarsmeddelande till klienten. Svaret inkluderar statuskoden 201 (Created) och detaljer om det nyskapade inlägget i JSON-format.
res.status(201).json(newPost);
Felhantering
Vi omsluter rutkoden i ett try-catch-block för att hantera potentiella fel under datahämtning eller begäranshantering. Alla fel som uppstår loggas till konsolen för felsökningsändamål:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
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);
}
});
Komplett kod för validateData.js-filen
// 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;
Tack för dina kommentarer!