[英]How do I serve an HTML file in Express from a directory which is a level above my server folder?
[英]How do I configure my Express server to render all of my content, not just my HTML file?
我正在尝试为我当前的项目构建一个服务器,但我是 Express 的新手。 我的文件目录如下所示:
root-directory
├── public
│ ├── css
│ │ └── styles.css
│ ├── images
│ │ └── img1.png
| | └── img2.png
| | └── img3.png
│ └── index.html
| └── main.js
└── server
└── app.js
这是我在服务器中使用的代码:
const express = require('express'); const path = require('path'); const app = express(); app.use('/static', express.static('public')); app.use(express.json()); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')) }); const port = 5000; app.listen(port, () => console.log(`Server is listening on port ${port}.`))
目前,服务器只显示我的 static HTML 文件,并且没有 JavaScript 或 Z2C56C360580485DFED23 链接到它。 我试图改变我的 sendFile function 看起来像这样: res.sendFile(path.join(__dirname, '../public'))
; 但这会导致Error: Cannot GET /
。
如何重新配置我的服务器以同时显示我的 HTML、CSS 和 JavaScript?
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../public/index.html'))
});
您不需要使用index.html
文件响应所有GET 请求(因为使用了 '*')。 此外,它与app.use('/static', express.static('public'));
行冲突。 .
/static
替换为/
app.use('/static', express.static('public'));
然后您的应用程序会在public
文件夹中找到index.html
以响应 GET '/' 请求。
index.html
文件是否指向 CSS/JS/图像文件的链接有效。 例如, style.css
文件的链接应该是: <link rel="stylesheet" href="/css/style.css">
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.