Serving static files in Express在Express中提供静态文件
To serve static files such as images, CSS files, and JavaScript files, use the 要提供静态文件,如图像、CSS文件和JavaScript文件,请使用Express中的express.static
built-in middleware function in 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
To use multiple static assets directories, call the 要使用多个静态资产目录,请多次调用expresstatic中间件函数:express.static
middleware function multiple times:
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按照您使用express.static
middleware function.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。