【问题标题】:Why does node.js app CSS load in my IDE but not on a localhost?为什么 node.js 应用程序 CSS 在我的 IDE 中加载,而不是在本地主机上?
【发布时间】:2014-09-24 06:34:02
【问题描述】:

我正在使用 LightTable 制作一个 nodejs 应用程序,当我在 <link href=""> 标记中指明文件的相对路径时,css 似乎加载正常。但是,当我运行node index.js 时,服务器启动并且页面加载正常,但是我收到控制台错误和我自己的 404,说在指定的路径中找不到 CSS 文件。我也尝试使用 Heroku 的Foreman Start,但没有骰子。这是html:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Home
        </title>
        <link href="../../styles/master.css" rel="stylesheet" type="text/css" />
    </head>
...

这是我的目录树结构:

.
├── Procfile
├── README.md
├── index.js
├── package.json
├── resources
│   └── images
│       └── tokyo.jpg
├── styles
│   └── master.css
└── views
    ├── get
    │   ├── home.html
    │   └── posts.html
    └── post
        └── new.html 

编辑:找到问题的答案后,以下信息变得相关。我已经注释掉了根据需要加载 CSS 和背景图像的新代码。

这是我的路由和服务器代码。我不是故意使用 Express:

    // routes
    var homeREGEX = new RegExp('^/?$');
    var newREGEX = new RegExp('^/posts/new/?$');
    var postsREGEX = new RegExp('^/posts/?$');
 // var cssREGEX = new RegExp('^/styles/master.css/?$');             <--| static resources also
 // var tokyoREGEX = new RegExp('^/resources/images/tokyo.jpg/?$');  <--| need routes. 

    // server
    var server = http.createServer(function(request, response){
      var pathname = url.parse(request.url).pathname;

      if (homeREGEX.test(pathname)) {
        renderHome(request, response);

      } else if (newREGEX.test(pathname)) {
        renderPostForm(request, response);
      } else if (postsREGEX.test(pathname)) {
        addNewPost(request, response);
   // } else if (cssREGEX.test(pathname)) {           <--| and they need to get
   //   sendCSS(request, response);                   <--| served individually as
   // } else if (tokyoREGEX.test(pathname)) {         <--| they are requested
   //   sendTokyo(request, response);
      } else {
        error404(request, response);
      }
    });

【问题讨论】:

  • 当您查看页面时在浏览器中看到的 URL 是什么,但它不起作用?
  • localhost:3000,但是如果我导航到 localhost:3000/styles/master.css,我得到一个 404 not found,错误。

标签: html css path localhost static-resource


【解决方案1】:

查看页面时您在浏览器中使用的网址是什么?我的猜测是它不包含views/get 部分,这意味着您不需要在链接href 属性中使用..\..

另外,请确保您实际上在提供这些静态文件(看来您不是)。例如,如果您使用 express(与 nodejs ),您将需要这样的东西:

app.use(express.static('resources'));
app.use(express.static('style'));

express.static documentation

【讨论】:

  • 我已经尝试在我能想到的每个组合中删除和添加“../”。还没用!
  • 好的,但是请提供你的网址,否则我们无能为力。
  • 我把它贴在上面:localhost:3000。在控制台中显示x-GET localhost:3000/styles/master.css,并在我导航到那里时确认了 404 not found 错误。
  • 您确定您确实在提供文件吗?查看我的更新答案。
  • 这实际上可能是我的问题。我没有使用 Express,因为我想了解内部结构,然后建立自己的框架。如何在没有 Express 的情况下执行 app.use 之类的操作?
【解决方案2】:

也许您可以尝试放置确切的路径而不是 ../../

<link href="/Procfile/styles/master.css" rel="stylesheet" type="text/css" />

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多