【问题标题】:Node.js server app not showing CSSNode.js 服务器应用程序未显示 CSS
【发布时间】:2025-12-20 05:55:06
【问题描述】:

我的 node.js 服务器上有以下代码(我正在使用 express):

app.get('/appointment/:id',function(req,res){
  res.writeHead(200,{'Content-Type':'text/html'});
  res.write('<link href="public/css/style.css" rel="stylesheet" type="text/css">');
  res.write('<form name="accept" action="http://localhost:8080/appointment/'+ req.params.id+'/1" method="post">');
  res.write('<input id="accept" type="submit" value="Accept">');
  res.write('</form><br>');
  res.write('<form name="decline" action="http://localhost:8080/appointment/'+ req.params.id+'/0" method="post">');
  res.write('<input id="decline" type="submit" value="Decline">');
  res.write('</form><br>');
  res.end();
});

在我的根文件夹中,我有文件夹约会/public/css/style.css。
当我打开网页时,它只显示 2 个表单按钮,但没有应用 CSS。
CSS代码是:

#accept {
  width:50px;
  height:30px;
  background-color:#00FF00;
  color:#FFFFFF;
  font-weight:bold;
  font-size:120%;
}

#decline {
  width:50px;
  height:30px;
  background-color:#FF0000;
  color:#FFFFFF;
  font-weight:bold;
  font-size:120%;
}

有什么问题,我该如何解决?

编辑:层次结构如下:
-server_files
--nodeServer.js
--公共
---css
----style.css

【问题讨论】:

  • 你能在另一个标签页中加载 CSS 文件吗?
  • 据我了解您使用的是快递,所以您需要将此行添加到您的代码app.use(express.static(__dirname + '/public'));,并在public/css/style.css之前添加/
  • @RienNeVaPlu͢s 不,我不是。当我单击链接时,它说它无法执行 GET 请求。我是否需要添加 app.get 并“提供”CSS 文件?
  • 是的,您需要像 Alexander 所描述的那样提供静态文件。祝你好运:)
  • @remaker 如果/public 是您的静态根目录,则http://localhost/foo.css 映射到文件public/foo.css。 (静态根目录的名称永远不会出现在静态 HTTP 路径中;文件系统的 public 成为服务器的 /(根))您需要在 &lt;link&gt; 中使用 /css/style.css

标签: html css node.js express


【解决方案1】:

我觉得与您分享这个问题发生的原因很重要。就像其他 Web 框架一样,ExpressJs 有自己的静态文件服务方式。

express.static 中间件基于serve-static,负责为 Express 应用程序的静态资产提供服务。

它是如何工作的:

  • 从应用目录中的“公共”目录为应用提供静态内容

    // GET /style.css 等

    app.use(express.static(__dirname + '/public'));

  • 将中间件挂载到“/static”以仅在其请求路径以“/static”为前缀时才提供静态内容

    // GET /static/style.css 等

    app.use('/static', express.static(__dirname + '/public'));

  • 提供来自多个目录的静态文件,但“./public”优先于其他目录

    app.use(express.static(__dirname + '/public'));

    app.use(express.static(__dirname + '/files'));

    app.use(express.static(__dirname + '/uploads'));

我检查了您的文件夹结构,我建议您将 public 目录与 server_files 目录保持在同一级别,并将 nodeServer.js 文件放在 server_files 之外 因为它是您用来启动应用程序的主文件。

然后在你的 nodeServer.js 中你可以这样做:

app.use('/public', express.static(__dirname + '/public'));

完成此操作后,您可以在 html 模板或您可能正在使用的任何其他模板引擎中访问公共目录中的所有静态资产。例如:

<link href="public/css/style.css" rel="stylesheet" type="text/css">

请注意nodeServer.js中你的中间件的顺序。我希望这会有所帮助。

【讨论】: