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中的express.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.有关选项参数的详细信息,请参阅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:要使用多个静态资产目录,请多次调用express.static中间件函数:

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. 但是,您提供给express.static函数的路径是相对于启动node进程的目录的。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 app,则使用您要服务的目录的绝对路径更安全:

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更多示例