jacobsowles
jacobsowles

Reputation: 3003

Express.js not finding stylesheet

I'm working on an app using the MEAN stack, and I'm having trouble getting my main index page to pick up my stylesheet. Running node server works fine, the index.html page is rendering, and there are no console errors. Hitting http://localhost:3000/public/css/app.css returns the CSS as expected. So the file is there and accessible, but the styles aren't being applied to the index page.

Any idea what's going on?

./server.js

var config = require('./server/config/environment');
var express = require('./server/config/express');

var app = express();

app.listen(config.port, function() {
    console.log('Server is listening on port %d', config.port);
});

exports = module.exports = app;

./server/config/express.js

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

module.exports = function() {
    var app = express();

    app.set('view engine', 'ejs');
    require('../server.routes.js')(app);
    app.use("/public/css", express.static(path.resolve('public/css')));
    app.get('/public/css/app.css', function(request, response) {
        response.sendFile(path.resolve('public/css/app.css'));
    });

    return app;
};

./server/server.routes.js

module.exports = function(app) {
    app.get('/', require('./server.controller').render);
};

./server/server.controller.js

module.exports.render = function(request, response) {
    response.render('index');
};

./views/index.ejs

<head>
    <base href="/">
    <link rel="stylesheet" src="/public/css/app.css">
</head>

./public/css/app.css

body {
    margin: 70px 20px 20px 20px;
}

Upvotes: 0

Views: 186

Answers (1)

aray12
aray12

Reputation: 1843

Try this

./views/index.ejs

<head>
    <base href="/">
    <link rel="stylesheet" href="/css/app.css">
</head>

./server/config/express.js

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

module.exports = function() {
    var app = express();

    app.set('view engine', 'ejs');
    require('../server.routes.js')(app);
    app.use(express.static(path.resolve(__dirname, 'public')));

    return app;
};

When you use express.static() you are registering that as a public folder, meaning the client doesn't need to actually know what the name of the folder is. Essentially what you were doing was calling

<head>
    <base href="/">
    <link rel="stylesheet" href="/public/css/public/css/app.css">
</head>

Usually people register a base folder and then put the css in the css/ subfolder and the js in the js/ subfolder

EDIT: @HydraHorn realized on his own that he was using <link src="..."> instead of <link href="...">. That said it still would not have worked without the changes to express.static(). I have made the changes above to not confuse future visitors

Upvotes: 1

Related Questions