我正在嘗試使用 node js 創建一個網站,并且我有 /home 和 /contact。一切正常,直到我將 css 和 js 都放在它們上并且第二次呼叫不起作用。我認為我首先訪問 /home (一切正常),然后我執行 /contact 并且頁面保持不變。
const PORT = 7777;
app.set('view engine','ejs');
app.get('/home',(req,res)=> {
console.log("get /home");
app.use(require("express").static('./views/Home'));
res.render('Home/home.ejs');
});
app.get('/contact',(req,res)=>{
console.log("get /contact");
app.use(require("express").static('./views/Contact'));
res.render('Contact/contatct.ejs');
});
app.listen(
PORT,
() => console.log(`it's alive on http://localhost:${PORT}`)
)
提前謝謝
uj5u.com熱心網友回復:
- 不需要多次。_ 在模塊頂部需要一次
expressexpress - 不要添加中間件來回應對特定頁面的請求。在應用程式加載時添加它。
- 不要將視圖模板與靜態檔案混合
app.set('view engine','ejs');
app.get('/home',(req,res)=> {
console.log("get /home");
res.render('Home/home.ejs');
});
app.get('/contact',(req,res)=>{
console.log("get /contact");
res.render('Contact/contatct.ejs');
});
app.use("/static", express.static('./static/'));
然后在您的 EJS 模板中:
<link rel="stylesheet" href="/static/file_name_in_static_folder.css">
要么
<img src="/static/image_used_in_one_template_but_stored_in_static_folder.png">
uj5u.com熱心網友回復:
檢查 'views/Contact/' 中的檔案名是 'contatct' 還是 'contact'
const PORT = 7777;
app.set('view engine','ejs');
app.get('/home',(req,res)=> {
console.log("get /home");
app.use(require("express").static('./views/Home'));
res.render('Home/home.ejs');
});
app.get('/contact',(req,res)=>{
console.log("get /contact");
app.use(require("express").static('./views/Contact'));
// here
res.render('Contact/contatct.ejs');
});
app.listen(
PORT,
() => console.log(`it's alive on http://localhost:${PORT}`)
)
如果沒有錯別字試試這個
const PORT = 7777;
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.get("/home", (req, res) => {
console.log("get /home");
res.render("Home/home.ejs");
});
app.get("/contact", (req, res) => {
console.log("get /contact");
res.render("Contact/contact.ejs");
});
app.listen(PORT, () => console.log(`it's alive on http://localhost:${PORT}`));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/428879.html
