Search code examples
cssexpressstaticpugstylesheet

Static files with Express


I am trying to link a stylesheet in a jade template, and am getting a 404. I have the exact path to the stylesheet, and have my app configured to serve up static files from my 'static' directory, but I am still getting a 404 ? Also why do static files need to be served up ? Why can't they just be linked to in your templates ?

'use strict';

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

app.set('view engine', 'jade')
app.set('views', __dirname + '/templates')

app.listen('3000', function(){
    console.log('Running on port 3000');
})

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

// Routes

app.get('/', function(request, response){
    response.render('index')    
});

app.get('/blog:id', function(request, response){
    response.send('This is the blog page.')
})

app.get('/about', function(request, response){
    response.send('This is the about page.')
})

Jade template

html
    head
        link(rel="stylesheet", href="../../static/css/normalize.css")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7", crossorigin="anonymous")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css", integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r", crossorigin="anonymous")
    body
        div.hero(style="width: 100%; height: 400px; background-color: blue")
            h1(style="color: white;") This is the landing page !
        script(src="https://code.jquery.com/jquery-2.2.3.min.js",   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=",   crossorigin="anonymous")
        script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS", crossorigin="anonymous")

Solution

  • You can have your css file url relative to the static folder

    link(rel="stylesheet", href="/css/normalize.css")