简体   繁体   English

带有 css 和 js 的 Express 服务器静态 ejs 文件不起作用

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

I am trying to make a website with node js, and I have /home and /contact.我正在尝试使用节点 js 制作一个网站,并且我有 /home 和 /contact。 Every thing works until I put css and js at both of them and the second call does not work.I am reffering that I acces first the /home (everything works), then I do /contact and the page remains the same.一切正常,直到我将 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}`)
)

thx in advance提前谢谢

  • Do not require express multiple times.不需要express多次。 Do require express once at the top of your module的模块的顶部 require express once
  • Do not add middleware in response to a request for a specific page.不要添加中间件来响应对特定页面的请求。 Do add it when the application loads.在应用程序加载时添加它。
  • Do not mix your view templates with your static files不要将视图模板与静态文件混合使用
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/'));

Then in your EJS templates:然后在您的 EJS 模板中:

<link rel="stylesheet" href="/static/file_name_in_static_folder.css">

Or要么

<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