首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法使样式表与node.js的ejs一起使用

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

Stack Overflow用户
提问于 2012-11-21 13:21:42
回答 5查看 37.5K关注 0票数 19

我试图用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");

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>

相对于app.js,样式位于style.css /style.css目录中

p {
  color:red;
}

我已经尝试了所有我能想到的链接href的路径,包括相对于我的本地主机相对于app.js的位置相对于相对于board.ejs的位置,甚至是相对于style.css的路径,但似乎都不起作用。我们非常感谢您的任何建议。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-11-21 14:03:09

声明一个静态目录:

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

<link rel='stylesheet' href='/style.css' />
票数 49
EN

Stack Overflow用户

发布于 2013-06-24 09:51:04

在app.js中:

 you must first declare static directory 

app.use("/styles",express.static(__dirname + "/styles"));

在ejs文件中:

<link rel='stylesheet' href='/styles/style.css' />
票数 12
EN

Stack Overflow用户

发布于 2019-09-19 17:42:43

最近我也在做同样的事情,我的CSS不工作了。最后,我终于掌握了诀窍。我的静态路径如下所示,

const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory =  express.static(publicDirectoryPath);
app.use(staticDirectory);

我的文件夹结构是这样的

诀窍是express access只定义了静态路径,在我的例子中CSS是在公共的外部,所以它不工作,突然我将CSS文件夹移动到我的公共文件夹内,仅此而已。效果很好。

上面的例子只针对一个静态路径。对于多个静态路径,您可以使用以下代码

const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory =  express.static(publicDirectoryPath);
const cssDirectory =  express.static(cssDirectoryPath);


app.use(staticDirectory);
app.use('/css/',cssDirectory);

我的通用HTML文件是

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
    <link rel="stylesheet"  href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13486838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档