如何配置我的 Express 服务器以呈现我的所有内容,而不仅仅是我的 HTML 文件?



我正在尝试为我当前的项目构建一个服务器,但我是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">

最新更新