Node.js自建静态文件服务访问index.html时为何输出多条req.url
静态资源服务运行场景说明
我开发了一款服务端应用,可读取指定目录下的index.html文件返回给前端。
服务端核心代码如下:
const http = require('http') const fs = require('fs') const port = process.env.PORT || 1337; const server = http.createServer(function (req, res){ if(req.url.match(/^\/static/)) return respondStatic(req,res) return respondNotFound(req,res) }); server.listen(port) function respondStatic(req,res){ const filename = `${__dirname}/public${req.url.split('/static')[1]}` fs.createReadStream(filename) .on('error',()=> respondNotFound(req,res)) .pipe(res) console.log(req.url); }
运行程序后,在浏览器中访问 http://localhost:1337/static/index.html,查看服务终端时发现,代码行console.log(req.url);共输出了3条结果:
/static/index.html /static/tachyons.min.css /static/ember.jpg
当前public目录下存放的文件清单如下:
chat.css chat.html chat.js ember.jpg index.html tachyons.min.css
其中tachyons.min.css和ember.jpg是index.html页面内引用的依赖资源。
核心疑问:
我仅在浏览器输入了index.html对应的静态文件访问地址,为何控制台会将另外两个静态文件路径也作为req.url打印输出?
问题解答
这个现象是浏览器加载网页的标准运行机制,和你的服务端代码逻辑没有冲突:
- 你在地址栏输入index.html的访问地址时,只会触发第一次HTTP请求,服务端收到请求后,会把index.html的完整文本内容返回给浏览器。
- 浏览器拿到返回的HTML内容后,会逐行解析标签,自动识别所有外部资源引用(比如
<link>标签引入的CSS、<img>标签引入的图片),对每一个引用的资源自动发起一次独立的HTTP请求。整个过程不需要手动触发,也不是服务端主动发起的。 - 控制台输出的3条日志,刚好对应三次完全独立的请求:
- 第一条是你手动输入地址触发的HTML文档请求
- 第二条是浏览器识别到index.html内引用了
tachyons.min.css,自动发起的样式文件请求 - 第三条是浏览器识别到index.html内引用了
ember.jpg,自动发起的图片资源请求
所有匹配/static开头的请求都会进入respondStatic函数,执行函数内的打印逻辑,因此三个请求的路径都会被输出到控制台。
你可以做个简单验证:把index.html内引入tachyons.min.css和ember.jpg的代码注释掉,再次访问页面,服务端就只会输出/static/index.html这一条日志,就能完全对应这个运行逻辑。
内容的提问来源于stack exchange,提问作者Dineth S Gimhana
相关产品推荐
相关产品推荐

