无法使样式表与node.js的ejs一起使用

Loo*_*urr 17 stylesheet ejs node.js express

我正在尝试使用node,express和ejs为模板创建一个简单的服务器.我已经让服务器指向页面,加载它,甚至能够使用include语句生成其他代码.但由于某种原因,样式表将无法加载.

app.js

var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');

var PORT = 8080; 

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

app.get('/', function(req, res){
res.render('board.ejs', {
    title: "anything I want",
    taco: "hello world",
    something: "foo bar",
    layout: false
  });
});


app.listen(PORT);
console.log("Server working");
Run Code Online (Sandbox Code Playgroud)

ejs文件位于目录views/board.ejs中

<html>
 <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='../styles/style.css' />
 </head>
 <body >
    <h1> <%= taco %> </h1>
    <p> <%=  something %> </p>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

和style.css位于相对于app.js的styles/style.css目录中

p {
  color:red;
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了每条路径,我可以设想链接的href包括相对于我的localhost相对于app.ejs相对于board.ejs的位置,甚至只是style.css,但似乎没有工作.任何建议都非常感谢.

cho*_*ovy 42

声明一个静态目录:

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

<link rel='stylesheet' href='/style.css' />
Run Code Online (Sandbox Code Playgroud)

  • 您基本上是在与您的 .ejs 文件交谈,并说当您引用静态文件时,就像上面的 `link` 标签一样,根目录是您在 app.use 中定义的 `public` 文件夹,而不是根目录整个应用程序。在这种情况下,链接标签的 href 中的“/”引用的是 `public` 目录,而不是应用程序的根目录。 (2认同)

ahm*_*mdy 12

在app.js中:

 you must first declare static directory 

app.use("/styles",express.static(__dirname + "/styles"));
Run Code Online (Sandbox Code Playgroud)

在ejs文件中:

<link rel='stylesheet' href='/styles/style.css' />
Run Code Online (Sandbox Code Playgroud)