【问题标题】:Path problem in URL ( absolute and relative )URL 中的路径问题(绝对和相对)
【发布时间】:2020-07-04 15:01:01
【问题描述】:

我有一个带有“Nodejs”的本地网站(使用“Express”框架)。我正在使用快速路由来显示我的目录中的每个文件,如果请求的文件不在我想要呈现的目录中 not-found.html。 但我意识到奇怪的事情发生了。 问题来了:

当用户输入如下内容时:“http://localhost:3000/swgw”最后一个中间件执行和“not-found.html”渲染属性。 (带有 css 样式)
当用户输入如下模式的 URL 时:“http://localhost:3000/products/*”问题是这次 not-found.html 渲染没有 css 样式。 (注意: * 不是 1-6)



  • 公开
    • 产品
      • product-1.html
      • product-2.html
      • product-3.html
      • product-4.html
      • product-5.html
      • product-6.html
    • 风格
      • not-found.css
    • not-found.html
  • server.js


    server.js

    ```
    ...
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.get("/products/:id", (req, res, next) => {
      // since I have six product with id from 1 to 6. 
      if (req.params.id <= 6 && req.params.id >= 1) {
        res.setHeader('content-type', 'text/html');
        return res.sendFile(path.resolve(`public/products/product-${req.params.id}.html`));
      }  
      else {
        next();
      }
    });
    
    app.get('*', function(req, res){
      res.status(404);
      res.sendFile(path.resolve('public/not-found.html'));
    });
    ```
    




    not-found.html ... <link rel="stylesheet" href="./style/not-found.css" > ...

【问题讨论】:

  • 更改为&lt;link rel="stylesheet" href="/style/not-found.css" &gt;。您需要一个相对于 express.static() 根目录的 public 目录的路径。
  • 谢谢,我的问题解决了。但是请你解释一下href="./style/not-found.css为什么当用户输入时它可以正常工作:“localhost:3000/5”但不能在“localhost:3000/products/5”上工作(我的意思是成功加载css)
  • 查看我在下面回答中的解释。
  • 您似乎只提供静态文件,完全放弃您的服务器代码并简单地使用 [http-server](使用 npmjs.com/package/http-server)会更简单

标签: javascript node.js express path


【解决方案1】:

改成

<link rel="stylesheet" href="/style/not-found.css" >. 

您需要一个相对于 express.static() 根目录的公共目录的路径。

但是请你解释一下 href="./style/not-found.css" 为什么当用户输入时它可以正常工作:“localhost:3000/5”但不能在“localhost:3000/products/”上工作5"(我的意思是加载css成功)

当您的 HTML 页面的链接不是以http:// 或/ 开头时,则认为它是路径相关链接,浏览器将获取页面的路径并将其与链接中的 URL 结合在将其发送到服务器之前制作完整的 URL。所以,当你有这个时:

href="./style/not-found.css"

页面网址是这样的:

http://localhost:3000/products/something

浏览器最终会请求:

http://localhost:3000/products/style/not-found.css

而且,您的服务器不知道如何处理它。另一方面,当您将&lt;style&gt; 标签更改为:

 href="/style/not-found.css"

然后,您的 URL 以 / 开头,因此浏览器将添加到其中的唯一内容是域并且浏览器将请求:

http://localhost:3000/style/not-found.css

这会起作用。

所以,当你使用这样的路径时:

http://localhost:3000/5

那么,它的路径就是/,所以当你把/和./style/not-found.css结合起来,浏览器最终会请求

http://localhost:3000/stye/not-found.css 

它会起作用,因为路径是根路径。因此,它不适用于不在顶层的页面。这就是为什么您的静态资源 URL 应该始终是绝对路径(以 / 开头),因此它们不依赖于托管页面的路径。

【讨论】:

  • 谢谢。我完全明白了。关于为nodeJS服务器设计路由有什么有用的文章或课程吗? (有效的方式)以及为什么某些代码对它们的静态文件使用不同的路径。 (可能是因为例如路由“/products”文件中有不同的css文件?或图像资源?)
  • @omid - 可以故意将所有相对 URL 用于嵌套目录,但在实践中,这样做可能会带来更多麻烦。您仍然可以轻松地在嵌套页面上使用绝对资源并使用不同的资源,而不会冒遇到您遇到的问题的风险。
猜你喜欢
  • 2011-11-15
  • 2011-04-29
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2013-07-14
  • 2010-12-17
  • 1970-01-01
相关资源
最近更新 更多