Serving static files in Express在Express中提供静态文件

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.要提供静态文件,如图像、CSS文件和JavaScript文件,请使用Express中的expres.static内置中间件函数。

The function signature is:函数签名为:

express.static(root, [options])

The root argument specifies the root directory from which to serve static assets.root参数指定从中提供静态资产的根目录。 For more information on the options argument, see express.static.有关options参数的更多信息,请参阅express.static

For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:例如,使用以下代码在名为public的目录中提供图像、CSS文件和JavaScript文件:

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

Now, you can load the files that are in the public directory:现在,您可以加载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
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.Express查找相对于静态目录的文件,因此静态目录的名称不是URL的一部分。

To use multiple static assets directories, call the express.static middleware function multiple times:要使用多个静态资产目录,请多次调用expresstatic中间件函数:

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

Express looks up the files in the order in which you set the static directories with the express.static middleware function.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:要为express.static函数提供的文件创建虚拟路径前缀(其中路径实际上不存在于文件系统中),请为静态目录指定装载路径,如下所示:

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

Now, you can load the files that are in the public directory from the /static path prefix.现在,您可以从/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

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:但是,您为express.static函数提供的路径是相对于启动node进程的目录的。如果你从另一个目录运行express应用程序,使用你想要服务的目录的绝对路径会更安全:

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.有关serve-static函数及其选项的更多详细信息,请参阅serve-static

Previous: Basic Routing基本路由     Next: More examples更多示例