【问题标题】:Express server public stylesheet not being fetched/applied未获取/应用 Express 服务器公共样式表
【发布时间】:2023-02-06 23:34:29
【问题描述】:

我正在学习如何使用 node、express 和 ejs 提供页面。我试图通过使用公共文件夹将样式表链接到 index.ejs,但是当我在浏览器中访问该页面时,没有样式,并且网络选项卡不显示对样式表的请求。当我转到 localhost:3000/styles.css 时,文件显示没有问题。这些文件如下所示:

索引.ejs

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sam's Site | <%= title %></title>
    <link rel="stylesheet" src="/styles.css" type="text/css">
  </head>

  <body>
  ...
  </body>
</html>

应用程序.js

const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.listen(3000);

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

app.get('/', (req, res) => {
  res.render('index', {title: 'Home');
});

app.js 在顶级文件夹中,index.ejs 在 vi​​ews 文件夹中,而 styles.css 在 public 文件夹中。当我在浏览器中检查它时,标头正常显示,链接标签看起来应该可以正常工作。

我已经尝试将源更改为 styles.css 路径的几种不同变体,并且我已确保样式包含有效的 css。谁能解释为什么没有加载样式表?

【问题讨论】:

    标签: css node.js express ejs


    【解决方案1】:

    use :

    app.use(express.static('public'))
    

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

    You are using public folder as default in express. So, no need to specify the path.

    • This is actually what I had before but changed it to try and fix the problem. Thanks for letting me know though.
    【解决方案2】:

    Your link tag should have an href attribute instead of src.

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 2020-03-24
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      相关资源
      最近更新 更多