利用 Express 托管静态文件
利用 Express 托管静态文件
为了提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件,请使用 Express 中的 express.static
内置中间件函数。
此函数特征如下:
express.static(root, [options])
The root
argument specifies the root directory from which to serve static assets. For more information on the options
argument, see express.static.
例如,通过如下代码就可以将 public
目录下的图片、CSS 文件、JavaScript 文件对外开放访问了:
app.use(express.static('public'))
现在,你就可以访问 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.static
中间件函数:
app.use(express.static('public')) app.use(express.static('files'))
访问静态资源文件时,express.static
中间件函数会根据目录的添加顺序查找所需的文件。
注意: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:
app.use('/static', express.static('public'))
现在,你就可以通过带有 /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
然而,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:
const path = require('path') app.use('/static', express.static(path.join(__dirname, 'public')))
欲了解更多关于 serve-static
函数及其参数的知识,请参考 serve-static。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现