I am trying to make a blog web app using node.js and express. I am trying to link to ejs files that were created in a blog-files directory using an a tag. I am quite new to programming (2-3 consistent months practice) so I’m finding backend difficult to understand. I should be able to view the files created from within the index.ejs file but it keeps showing an error such as:
Cannot GET /blog-files/2024-04-06_09-22-51.ejs
Index.ejs code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cooper's Blog</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<%- include("form-create.ejs") %>
<h3>Recent Blog Posts</h3>
<ul>
<% files.forEach((file)=> { %>
<li><a href="/blog-files/<%= file %>">
<%=file%>
</a>
</li>
<% }); %>
</ul>
</body>
</html>
app.js code
import express from "express";
import bodyParser from "body-parser";
import fs from "fs";
import { v4 as uuidv4 } from "uuid";
const app = express();
const port = 3000;
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
const blogDirectory = "./views/blog-files";
fs.readdir(blogDirectory, (err, files) => {
if (err) {
console.log(`Error reading directory:`, err);
res.status(500).send("Error reading directory");
return;
} else {
res.render("index.ejs", { files });
}
});
});
app.post("/submit", (req, res) => {
//Assign title and content
const title = req.body["post-title"];
const content = req.body["post-content"];
//Assign file content
let fileContent = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
${title}
</title>
</head>
<body>
<h3>
${title}
</h3>
<p>
${content}
</p>
</body>
</html>`;
//Generate file name based on current date and time
const curDate = new Date();
const fileName = `./views/blog-files/${curDate.getFullYear()}-${(
curDate.getMonth() + 1
)
.toString()
.padStart(2, "0")}-${curDate
.getDate()
.toString()
.padStart(2, "0")}_${curDate
.getHours()
.toString()
.padStart(2, "0")}-${curDate
.getMinutes()
.toString()
.padStart(2, "0")}-${curDate
.getSeconds()
.toString()
.padStart(2, "0")}.ejs`;
//Write the file content to an ejs file
fs.writeFile(fileName, fileContent, (err) => {
if (err) {
console.log(`Error writing file: ${err}`);
res.status(500).send("Error writing file");
return;
} else {
console.log(`File written successfully: ${fileName}`);
res.render("template.ejs", { title, content });
}
});
});
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
});