我有一个提供html的应用程序,如下所示。
// ...
var staticPath = config.development.staticFiles;
app.get('/category/:catName', function(req, res) {
res.sendFile(path.join(__dirname, staticPath + "shop-grid.html"));
})
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, staticPath + "index.html"));
})
// ...
在每个html中,css都是这样链接的。
<link rel="stylesheet" href="css/style.css" type="text/css">
index.html 可以正常工作,但是“ shop-grid.html” 不能与CSS一起加载,因为它试图在“ localhost:8080”上加载CSS / 类别 /css/style.css”,而不是“ localhost:8080 / css / style.css”,它适用于第一个html。
我在这里做什么错了?
答案 0 :(得分:2)
困扰我的是为什么相对路径发生了变化?这些html位于同一目录中,仅更改了url。
浏览器对您如何在服务器上存储文件一无所知。
仅知道网址。
css/style.css
是相对路径。
通过获取当前页面的URL,删除路径中最后一个/
之后的所有内容,然后附加相对路径,可以解决相对路径。
http://localhost:8080/
+ css/style.css
= http://localhost:8080/css/style.css
http://localhost:8080/category/cats
+ css/style.css
= http://localhost:8080/category/css/style.css
使用绝对路径:/css/style.css
。
通过删除整个路径(即主机名和端口号(如果有)之后的所有内容),然后附加绝对路径,可以解决绝对路径。
答案 1 :(得分:0)
您正在重定向这两种情况,因此更改了您的_dirname。但是,当您加载shop-grid.html时,您将完全重定向到另一个目录。 href路径不是全局路径,而是相对路径。