在我们访问网页过程中,经常会见到:http://localhost:3000/images/kitten.jpg 这样形式的url用来访问一个特定的文件。在express中我们可以使用Express 中的 express.static 内置中间件函数提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件。
我们可以看下源码注释:
/**
* Create a new middleware function to serve files from within a given root directory.
* The file to serve will be determined by combining req.url with the provided root directory.
* When a file is not found, instead of sending a 404 response, this module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs.
*/
其使用也很简单,使用如下形式:
app.use(express.static(path.join(__dirname, 'public')));
其中pulbic是我们包含静态资源的目录,向 express.static 函数提供的路径相对于我们在其中启动 node 进程的目录。如果从另一个目录运行 Express 应用程序,那么对于提供资源的目录使用绝对路径会更安全。所以我们推荐上面的写法。
关于静态目录的查找顺序:Express 会使用 express.static 中间件函数设置静态目录的顺序来查找文件。
如果我们要为 express.static 函数提供的文件创建虚拟路径前缀(路径并不实际存在于文件系统中),我们需要为静态目录指定安装路径,如下所示:
app.use('/static', express.static('public'));
此时我们可以通过下面的形式访问指定文件
http://localhost:3000/static/images/kitten.jpg
特别注意:Express 相对于静态目录查找文件,因此静态目录的名称不是此 URL 的一部分。