Can't get stylesheet to work with ejs for node.js


Question

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.

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");

The ejs file is in a directory 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>

and style.css is in a styles/style.css directory relative to app.js

p {
  color:red;
}

I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.

1
17
11/21/2012 5:27:18 AM

Accepted Answer

Declare a static directory:

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

<link rel='stylesheet' href='/style.css' />
43
11/21/2012 6:03:08 AM

in app.js:

 you must first declare static directory 

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

in ejs file :

<link rel='stylesheet' href='/styles/style.css' />

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon