将CSS样式表与express.static问题链接

时间:2019-11-11 18:23:25

标签: css express static

我只是在学习,所以需要一些帮助。

当我尝试将html文件加载到本地服务器上时,它不会加载styles.css文件。

我在我的“公共”文件夹上使用了express.static,并修改了html文件中styles.css的路径。一些帮助会很棒。谢谢。

文件夹路径:css

  

C:\ Newsletter-Signup \ public \ css \ styles.css

我尝试在其上应用了.css的

html文件:

  

C:\ Newsletter-Signup \ public \ signup.html

!(https://imgur.com/PJO7J4H

这是我的app.js文件:

const app = express();

app.use(express.static("public"));

app.get("/", function(req, res){
  res.sendFile(__dirname + "/signup.html" );
});

app.listen("3000", function(){
  console.log("server started on port 3000");
});

这是我指向无法加载的styles.css的链接:

< link href="css/styles.css" rel="stylesheet" > 

1 个答案:

答案 0 :(得分:0)

在这里,我想为您介绍一个通用的解决方案。因此,这可能有助于解决在尝试代码时发生的问题。

生成Express应用程序项目时,我使用了Express Js官方网站中推荐的命令npm install -g express-generator。由此,我可以轻松地为Express应用创建文件夹结构。

enter image description here


.pug文件格式

默认情况下,生成的Express应用仅允许您呈现.pug文件格式,而不是.html文件格式。 Express-generator通过npm install pug -- save安装pug节点模块,同时安装其他必需的依赖项。安装pug依赖项后,允许渲染.pug文件使用localhost URL在根目录中。

app.js

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res, next) {
  res.render('<pug file name>', { title: 'Express' });
});

将当前目录设置为应用程序根目录,并从终端运行命令npm start并访问URL http://localhost:<Port Name>/

然后您可以看到渲染的.pug文件。


获得对.html文件格式的支持

由于Express Js支持.pug文件格式,因此您需要安装ejs节点模块以获得对.html格式的支持。

npm install ejs --save

然后需要如下更新app.js文件内容

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res, next) {
  res.render('<html file name>', { title: 'Express' });
});

现在您将看到.html文件已正确呈现。


添加样式表以表示应用

app.js文件中,已经为静态文件设置了目录路径,如下所示。

app.use(express.static(path.join(__dirname, 'public')));

这意味着public文件夹被设置为静态文件目录。 因此,在head标签内链接样式表时,样式表的相对路径应声明为'stylesheets/style.css

<head>

  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" type="text/css" href="stylesheets/style.css">

</head>
相关问题