翻译此页面

在 Express 中托管静态文件

要托管图片、CSS 文件和 JavaScript 文件等静态文件,需使用 Express 内置的 express.static 中间件函数。

该函数的签名为:

express.static(root, [options]);

root 参数用于指定托管静态资源的根目录。 For more information on the options argument, see express.static.

例如,使用以下代码来托管 public 目录中的图片、CSS 文件和 JavaScript 文件:

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

现在,你就可以加载 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

Note

Express 查找文件时是相对于静态目录的,因此静态目录名称不会出现在 URL 中。

若要使用多个静态资源目录,需多次调用 express.static 中间件函数:

app.use(express.static('public'));
app.use(express.static('files'));

Express 会按照你使用 express.static 中间件设置静态目录的顺序来查找文件。

Note

For best results, use a reverse proxy cache to improve performance of serving static assets.

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

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

现在,你可以通过 /static 路径前缀加载存放在 public 目录中的文件。

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

但是,你提供给 express.static 函数的路径是相对于你启动 node 进程的目录而言的。 如果你从其他目录启动 Express 应用,使用你要托管的目录的绝对路径会更安全:

index.cjs
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));

For more details about the serve-static function and its options, see serve-static.