我正在尝试为我当前的项目构建一个服务器,但我是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}.`))
目前,服务器只显示我的静态HTML文件,没有链接到它的JavaScript或CSS。我尝试将我的 sendFile 函数更改为如下所示: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">
。