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

When I add ```'/static'``` as the first parameter for app.use(), the app crashes.

When I add '/static' as the first parameter for app.use(), the app crashes with error

/Users/henrymorrow/Documents/treehouse-express-basics/node_modules/express/node_modules/serve-static/index.js:48
  var opts = Object.create(options || null)
                    ^

TypeError: Object prototype may only be an Object or null: /Users/henrymorrow/Documents/treehouse-express-basics/src/public

When I take the '/static' out, the app works fine. Not sure what is going wrong in this step though it looks like something I am missing in express maybe?

My app.js code.

'use strict';

//requiring for express and posts object
var express = require('express');
var posts = require('./mock/posts.json');

var app = express();

//activate static server
app.use(express.static('/static', __dirname + '/public')); //express is referenced directly and .use sets up the static server. '/static' is the first argument so the prefix can be use to find public files with the url 

//Sets app to understand and find jade files
app.set('view engine', 'jade');
app.set('views', __dirname + '/templates')

//renders the index.jade file
app.get('/', function (req, res) { //req and res are request and response
    res.render('index')
});

//reders the post json object and takes the title key in the object to fit the end of the url as a parameter
app.get('/blog/:title?', function (req, res) {
    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});
    }
})

//Listens to port 3000 and displays message in the console to let you know app is running
app.listen(3000, function () {
    console.log("The frontend server is running fast on port 3000!");
});

1 Answer

You are using the method incorrectly.

Express static files docs

Try this.

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

or this.

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

Worked thanks! I see my error now.