Recently, I utilized Express and EJS for a project of mine. My goal was to have a .ejs file rendered when accessing "localhost:PORT/posts/:articleName". However, I encountered an issue even though I included the line
app.use(express.static(__dirname + "/public"));
. The problem lies in the fact that when inspecting the stylesheet link within the post.ejs file, it displays as "localhost:PORT/posts/style.css" instead of "localhost:PORT/style.css", which is necessary for proper functioning. How can I rectify this path discrepancy?
Here is the structure of my project: https://i.sstatic.net/DRkNw.jpg
The following code pertains to the GET request for /
app.get("/posts/:articleName", (req, res) => {
for(obj of posts) {
if(lodash.lowerCase(obj.title) === lodash.lowerCase(req.params.articleName)) {
console.log("it's a match");
res.render("post.ejs", {title: obj.title,
content: obj.content});
return;
}
}
res.redirect("/");
});
posts = array of JSON objects
post.ejs = the file containing only specific articles. Unfortunately, it fails to load the style.css file from the public directory as intended.