Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics (2015) Serving Static Files in Express Setting Up the Express Static Server in Development

Gustavo Buarque
Gustavo Buarque
7,113 Points

express.static is not working at localserver

I'm trying to follow along this course in my computer. Until everything worked. But I'm trying to get the static files but it is not working. When I try to access the css file there is this result: Cannot GET /static/css/bootstrap.min.css

I tried to debug, and I could see those functions app.use and express.static, but I couldn't figure out how to access the data inside those.

See my code in app.js bellow:

'use strict';

var express = require('express'),
    posts = require('./mock/posts.json');

var app = express();

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


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

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

app.get('/blog/:title?', function(req, res){
    //debugger;
    var title = req.params.title;
    if(title === undefined) {
        res.status(503)
        res.send("This page is under construction!");
    } else {
        var post = posts[title] || {};
        res.render('post', {post: post});   
    }

});

// Start the http-server in http://localhost:3000/
app.listen(3000, function(){
    console.log("The frontend server is running on port 3000!");
});

3 Answers

Jesus Mendoza
Jesus Mendoza
23,289 Points

Try

app.use('/static', express.static(path.join(__dirname + 'public')));
Gustavo Buarque
Gustavo Buarque
7,113 Points

Hello Jesus,

I was trying to fix, then I tried: app.use('/static', expres.static());

And then it worked. So I saw that I created the public directory outside the src directory. Then I've just moved the public directory to the correct path, and it worked.

Thank you.

Alexander Køpke
Alexander Køpke
5,065 Points

Was going nuts over why it didn't work. I even changed it back to app.use(express.static(__dirname + "/public"); and somehow I couldn't access it localhost:3000/css/bootstrap.css but could if I went to localhost:3000/static/css/bootstrap.css.

Then I realized that I still had the old app.js open from the previous video but was serving the new app.js with nodemon. So closed atom down, closed nodemon, typed atom ., and within a minute it all worked as it should. LOL on me!