【发布时间】:2021-09-01 14:16:04
【问题描述】:
假设我的 index.js 与我的 index.html 位于同一目录中。还有一个包含styles.css的文件夹css。
/
|- index.js
|- index.html
|- css/styles.css
在 index.html 中,我可以使用相对路径指定我的 css 样式,它将指向相对于我的 index.html 的 css/styles.css
<link rel="stylesheet" href="css/styles.css">
但是,在 index.js 中,当我的 express 服务器收到 GET 请求而不是
app.get("/", function(req, res) {
res.sendFile("index.html"); // type Error
});
我必须指定一个绝对路径
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
考虑 index.html 在可以正确定位(显示无错误)相对路径 css/styles.css 时的行为。为什么不能对 index.js 应用相同的逻辑?
为什么文件系统的行为与我在 index.html 中指定相对路径时的行为不同?
注意:我知道另一种方法是指定根。但是,问题的重点是为什么我必须使用绝对路径而不是相对路径(为什么会出错?)
【问题讨论】:
-
您不需要手动发送 index.html。如果您只需使用
app.use( express.static( assetsFolderPath ) )指定其所在的文件夹,Express 将为您完成此操作
标签: javascript express http path web-development-server