模板引擎样式渲染不起作用

问题描述 投票:0回答:1

CSS 未渲染:

CSS 在单级路径中渲染,如 /、/users 等...CSS 不在 /admin/add-user 内渲染。

我的文件夹结构:

Please here to view image

index.js:

const express = require('express');
const http = require('http');
const index = express();
const path = require('path');
const dirPath = require('./utils/dirPath');

index.set('view engine', 'ejs');
index.set('views', 'views');
index.use(express.urlencoded({ extended: false }));

index.use(express.static(path.join(dirPath, 'public')));

const home = require('./routes/home');
const get404 = require('./routes/404');
const usersList = require('./routes/usersList');
const addUser = require('./routes/addUser');

index.use('/admin', addUser);
index.use('/', usersList);
index.use('/', home);
index.use(get404);

const server = http.createServer(index);
server.listen(5000);

addUser.ejs:

<%- include("includes/header.ejs")%>
    <%- include("includes/navigation.ejs")%>
<body>
    
    <main>
        <article>
            <form action="/add-user" method="post">
                <input type="text" name="username">
                <input type="submit" value="Submit">
            </form>
        </article>
    </main>
</body>
<%- include("includes/footer.ejs")%>

标题.ejs:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Home page</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
node.js ejs template-engine
1个回答
0
投票

您的 css 在某些视图中呈现,但不在进一步的嵌套路由中呈现,这一事实表明您解析目录的方式存在问题。由于您还没有分享

./utils/dirPath
的内容,所以很难说。

但是,由于您使用的是 CommonJS,我建议您只使用

__dirname
来设置静态
public
文件夹,如下所示:

index.use(express.static(path.join(__dirname, '/public')));
© www.soinside.com 2019 - 2024. All rights reserved.