0

I'm trying to use stylesheets and javascript files on my node.js project which uses express and ejs.

my structure:

public/
  -- css/
  -- js/
  -- images/

and my chat.ejs file:

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body>

.. content ..

    <% include ../partials/footer %>

</body>
</html>

and in my partials/head.ejs there is code

<link href="public/css/custom.css" rel="stylesheet">

and it should load style file but it doesn't. Btw my main chat.js:

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

// set the view engine to ejs
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));

// index page
app.get('/', function(req, res) {
    res.render('pages/chat');
});

app.listen(3000, function(){
    console.log('listening on *:3000');
});

so how to use it properly?

1 Answer 1

2

The public folder won't actually be part of the URL paths available to the client:

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

The path you give to express.static() will be combined with the URL path to the effect of:

// GET /css/custom.css
(__dirname + '/public') + '/css/custom.css'

So, when requesting public/css/custom.css, express.static() will try to find:

// GET /public/css/custom.css
(__dirname + '/public') + '/public/css/custom.css'

Expecting the folder structure to instead be:

public/
  -- public/
      -- css/
      -- js/
      -- images/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.