🌐 Nodejs.cn

在 Express 中提供静态文件

要提供静态文件,例如图片、CSS 文件和 JavaScript 文件,请在 Express 中使用 express.static 内置中间件函数。

🌐 To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

函数签名为:

🌐 The function signature is:

express.static(root, [options]);

root 参数指定用于提供静态资源的根目录。 有关 options 参数的更多信息,请参阅 express.static

🌐 The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.

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

🌐 For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

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

现在,你可以加载位于 public 目录中的文件:

🌐 Now, you can load the files that are in the public directory:

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 looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

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

🌐 To use multiple static assets directories, call the express.static middleware function multiple times:

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

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

🌐 Express looks up the files in the order in which you set the static directories with the express.static middleware function.

Note

为了获得最佳效果,使用反向代理 缓存来提高静态资源提供的性能。

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

要为由 express.static 函数提供的文件创建一个虚拟路径前缀(路径在文件系统中实际上并不存在),请指定静态目录的挂载路径,如下所示:

🌐 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 目录中的文件。

🌐 Now, you can load the files that are in the public directory from the /static path prefix.

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 应用,使用你想要提供服务的目录的绝对路径会更安全:

🌐 However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

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

有关 serve-static 函数及其选项的更多详细信息,请参见 serve-static

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