I have used Express and EJS for my project. I would like that when I enter "localhost:PORT/posts/:articleName", a .ejs file to be rendered. The only problem is that even if I have app.use(express.static(__dirname "/public"));
it doesn't work like it should. When I am inspecting the stylesheet link in the post.ejs file, it is "localhost:PORT/posts/style.css". But I want the path to be "localhost:PORT/style.css" in order to work. How can I fix the path?
Project structure: https://imgur.com/a/UrYY9lK
Code for 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 article, it doesn't work as it should, because it doesn't load the style.css file from public directory.
CodePudding user response:
Try this variant, because you wrote this part of code incorrect:
app.use(express.static('public'));
CodePudding user response:
Apparently, you need to have a "/" before your css file or put it in another subdirectory to get the correct path
so link rel="stylesheet href="/style.css"
does work, but link rel="stylesheet href="style.css"
doesn't.