我刚刚在 heroku 上部署了我的网络应用程序;它没有渲染,所以我添加了
app.get('/',(req,res) =>{
res.sendFile(path.join(__dirname, '../index.html'))
})
在 server.js 中。但是索引 CSS 样式和其他页面没有呈现。
这是我的文件夹结构:https://github.com/Adegbite1999/MyDiary
PS:我使用的是纯 HTML、CSS 和 JavaScript;没有框架或库。我该如何解决这个问题?
答案 0 :(得分:0)
看看你的回购,你有:
app.use(express.static((__dirname + '../UI/styles')))
app.use(express.static(__dirname + '../UI/images'))
但是你是这样引用的:
<head>
<!-- ... -->
<link rel="stylesheet" href="./UI/styles/index.css">
</head>
<body>
<!-- ... -->
<script src="./UI/lib/index.js"></script>
</body>
这不是 express.static
的工作方式。看看docs(强调):
例如,使用以下代码在名为 public 的目录中提供图像、CSS 文件和 JavaScript 文件:
app.use(express.static('public'))
现在,您可以加载公共目录中的文件:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Express 查找与静态目录相关的文件,因此静态目录的名称不是 URL 的一部分。
目前,express 会这样解释您的请求:
./UI/styles/index.css
:
__dirname + '../UI/styles' + '/UI/styles/index.css'
:未找到__dirname + '../UI/images' + '/UI/styles/index.css'
:未找到要么更改您的链接以匹配您的 express 服务器中指定的根(即将 href="./UI/styles/index.css"
更改为 href="index.css"
),或者更改您的 express 配置以使用虚拟路径(也在 docs ):
app.use(express.static('/UI/styles', __dirname + '../UI/styles'));
app.use(express.static('/UI/images', __dirname + '../UI/images'));
如果可能的话,我建议有一个主要的静态目录。你可以这样做:
app.use(express.static(__dirname + '../UI'));
// reference it in markup like: href="/styles/index.css"