CSS 未渲染:
CSS 在单级路径中渲染,如 /、/users 等...CSS 不在 /admin/add-user 内渲染。
我的文件夹结构:
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>
您的 css 在某些视图中呈现,但不在进一步的嵌套路由中呈现,这一事实表明您解析目录的方式存在问题。由于您还没有分享
./utils/dirPath
的内容,所以很难说。
但是,由于您使用的是 CommonJS,我建议您只使用
__dirname
来设置静态 public
文件夹,如下所示:
index.use(express.static(path.join(__dirname, '/public')));