使用 express js 服务 css

Serving css with express js

我在使用 express js 服务 css 时遇到了很多麻烦。我终于弄明白了,但是我有点困惑为什么我的新代码可以工作,而我的旧代码却不行。这是我的新代码,确实有效:

const express = require('express');
const path = require('path');

const app = express();
const port = process.env.PORT || 5010;

console.log(__dirname)
app.use('/public', express.static('public'));
app.set('views', path.join(__dirname, 'views'))

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'home.html'));
});

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

我的文件系统是这样的:

index.js
public
  css
    home.css
views
  home.html

最初而不是:

app.use('/public', express.static('public'));

我有:

app.use(express.static(path.join(__dirname, 'public')));

为什么第二个版本有效,而第一个版本无效?第二个版本中第一个参数的目的是什么?另外,为了以防万一,我正在 replit.com.

上编码

使用 1 个参数时

app.use(express.static(path.join(__dirname, 'public')));

此代码提供当前目录的“public”子目录中的文件。在 public/css/home.css 访问文件的 URL 是:http://localhost/css/home.css

使用2个参数时

app.use('/public', express.static('public'));

此代码还提供当前目录的“public”子目录中的文件,虚拟路径前缀为“/public”。因此,访问 public/css/home.css 处的文件的 URL 是:http://localhost/public/css/home.css

我们可以将第一个参数更改为任何内容,例如,如果我们有:

app.use('/static', express.static('public'));

然后相同文件的 URL 变为:http://localhost/static/css/home.css.

您可以从官方文档中找到更多信息here