幾個月前開始編碼,遇到了一個我在網上找不到任何東西的問題。我有以下 http 請求
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 });
});
所有渲染的模板都在同一個檔案夾中,但是當我嘗試從 /courses/:id 渲染某些內容時,它找不到合適的 css 和 js 檔案。僅當我使用 /courses/其他東西時才會出現問題。如果我只使用 /:id 嘗試相同的操作,它會加載正常,否則我會收到這些錯誤。
我在包含檔案中的路徑是:
<link rel="stylesheet" href="static/stylesheets/footer.css" />
<link rel="stylesheet" href="static/stylesheets/navbar.css" />
<link rel="stylesheet" href="static/stylesheets/coursesIndex.css" />
我嘗試了很多不同的可能路徑,但沒有任何運氣。感謝您的時間
uj5u.com熱心網友回復:
嘗試在靜態路徑之前添加前綴 a /,如下所示:
<link rel="stylesheet" href="/static/stylesheets/footer.css" />
<link rel="stylesheet" href="/static/stylesheets/navbar.css" />
<link rel="stylesheet" href="/static/stylesheets/coursesIndex.css" />
它可能會起作用,因為其他 2 條路由是根級路由。因此,在渲染時,瀏覽器會static/stylesheets/...在根目錄中查找。所以,它奏效了。但是,當您在/courses/:id路徑上呈現相同的內容時,瀏覽器會在static/stylesheets/...內部查找/courses/:id(例如,實際情況類似于/courses/1)。該目錄(1在示例中)在您的根目錄中不存在。
因此,如果您使用絕對路徑(這些是以 開頭的路徑/),瀏覽器將root始終從您的網站中查找它們。所以,這會奏效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461874.html
