簡體   English   中英

帶有 css 和 js 的 Express 服務器靜態 ejs 文件不起作用

[英]Express server static ejs file with css and js does not work

我正在嘗試使用節點 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}`)
)

提前謝謝

  • 不需要express多次。 的模塊的頂部 require express once
  • 不要添加中間件來響應對特定頁面的請求。 在應用程序加載時添加它。
  • 不要將視圖模板與靜態文件混合使用
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">
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}`));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM