利用 Express 托管静态文件
为了提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件,请使用 Express 中的 express.static
内置中间件函数。
此函数特征如下:
js
express.static(root, [options])
root
为静态文件的根目录。options
为可选项,包括maxAge
和index
两个选项。
例如,通过如下代码就可以将 public
目录下的图片、CSS 文件、JavaScript 文件对外开放访问了:
js
app.use(express.static('public'))
现在,你就可以访问 public
目录中的所有文件了:
js
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.static
中间件函数:
js
app.use(express.static('public'))
app.use(express.static('files'))
访问静态资源文件时,express.static
中间件函数会根据目录的添加顺序查找所需的文件。
注意:为了获得最佳效果,请使用反向代理缓存来提高提供静态资产的性能。
express.static
要为函数提供的文件创建虚拟路径前缀(其中路径实际上并不存在于文件系统中) ,请为静态目录指定挂载路径,如下所示:
js
app.use('/static', express.static('public'))
现在,你就可以通过带有 /static
前缀地址来访问 public
目录中的文件了。
js
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 应用程序,则使用要服务的目录的绝对路径更安全:
js
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))