在 Express 中提供静态文件

¥Serving static files in 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

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:

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.