【问题标题】:css file not considered when more than one route used with express, ejs当多个路由与 express、ejs 一起使用时,不考虑 css 文件
【发布时间】:2020-08-12 17:18:28
【问题描述】:

如果我使用app.get("/compose")app.get("/dynamic")- 即-单路由,我的CSS 文件将生效并且h1p 的样式会相应地设置,但如果我使用app.get("/posts/dynamic") - 那是 - 双路,我的 CSS 文件没有被考虑在内,尽管页眉和页脚工作正常

我的app.js 文件:

   const express = require("express");
   const app = express();

   app.use(express.static(__dirname + "/public"));

app.get("/compose", function(req, res) {
res.render("compose");
});

app.get("/posts/dynamic", function(req, res) {
res.render("dynamic");
});

app.listen(3000, function() {
console.log("started running on port 3000");
});

我的dynamic.ejs 文件:

<%- include("header"); -%>

<h1> Test </h1>
<p> Test Paragrapgh Content <p>

<%- include("footer"); -%>

我的contact.ejs 文件:

<%- include("header"); -%>

<h1> Contact Us </h1>
<p> Contact Us Content </p>

<%- include("footer"); -%>

我的express.static(); 是不是哪里出错了?

【问题讨论】:

    标签: javascript css node.js express ejs


    【解决方案1】:

    在这里,我尝试和工作。

    1. EJS 设置一个view Engine

      app.set('view engine', 'ejs');
      
    2. 然后添加

      app.use(express.static('public'));
      

    并假设您的文件夹结构是:

    project root 
         ├── server.js
         ├── package.json 
         └── public   
           ├── css  
             └── style.css
    

    在你的header.ejs 中添加这一行

    <link rel="stylesheet" href="/css/style.css" type="text/css">
    

    你的dynamic.ejs 文件是

    <%- include('./header.ejs'); %>
    
    <h1> Test </h1>
    <p> Test Paragrapgh Content <p>
    
    <%- include('./footer.ejs'); %>
    

    加法

    也可以同时定义多个文件夹

    app.use(express.static('public')); 
    app.use(express.static('images')); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 2020-06-22
      • 2015-08-13
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多