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.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 有关选项参数的详细信息,请参阅express.static。options argument, see 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 要使用多个静态资产目录,请多次调用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按照您使用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. 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。
