在地址栏中输入 http://localhost:3000/test 时,以下测试代码将按预期工作。
这是来自app.js
app.get("/test", (req, res) => {
res.sendFile(__dirname + "/public/index.html");
});
app.use(express.static("public"));
这是来自index.html
<img src="images/cat.jpg">
但是,当我在地址栏中输入 http://localhost:3000/test/ (请注意在末尾附加/
)时,index.html会被投放,但cat.jpg图片显示为断开的链接。
我可能缺少一个基本概念,但我不明白为什么多余的/
会中断图像链接,但仍提供index.html。为什么不能同时破坏它们或两者都不破坏?
答案 0 :(得分:1)
由于浏览器如何解析URL。当浏览器试图获取图像时,您的第一个URL将解析为http://localhost:3000/images/cat.jpg,因为原始URL以资源/test
结尾。
URL的第二个版本,您将其作为目录/test/
结束,因此图像的解析URL将为http://localhost:3000/test/images/cat.jpg。