started coding a couple of months ago and run into a problem I didn't find anything online. I have the following http requests
app.get("/courses", async (req, res) => {
const courses = await Course.find({});
res.render("courses/index", { courses, topic: "Μαθήματα" });
});
app.get("/about", (req, res) => {
res.render("courses/about", { topic: "Πληροφορίες" });
});
app.get("/courses/:id", async (req, res) => {
const { id } = req.params;
const course = await Course.findById(id);
return res.render("courses/show", { course, topic: course.title });
});
All of the rendered templates are in the same folder but when I try to render something from /courses/:id it can't find the appropriate css and js files. The problem appears only when I use /courses/something else. If I try the same thing with just /:id it loads fine, else I get these errors.
The paths I have in my include files are:
<link rel="stylesheet" href="static/stylesheets/footer.css" />
<link rel="stylesheet" href="static/stylesheets/navbar.css" />
<link rel="stylesheet" href="static/stylesheets/coursesIndex.css" />
I tried a ton of different possible paths by didn't have any luck. Thank you for your time
CodePudding user response:
Try prefixing a /
before the static paths, as follows:
<link rel="stylesheet" href="/static/stylesheets/footer.css" />
<link rel="stylesheet" href="/static/stylesheets/navbar.css" />
<link rel="stylesheet" href="/static/stylesheets/coursesIndex.css" />
It might work, because, the other 2 routes are root level routes. So, when rendered, browser would look for static/stylesheets/...
in the root directory. So, it worked.
But, when you rendered the same on /courses/:id
path, the browser would look for static/stylesheets/...
inside /courses/:id
(actual would be like /courses/1
, for example). That directory(1
in the example) does not exists in your root directory.
So, if you use absolute paths(these are the paths that starts with /
), browser would look for them from the root
of your website always. So, this would work.