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
Michael Brown
17,651 PointsNodejs Express server not working
So I was wondering if anyone could help me, I've hit a roadblock in my project where I am trying to set up a local server with nodejs and express. I have tried everything from google, stack overflow, and a myriad of blog articles on the topic - but no dice. I have tried writing different routes for each file, and that worked for the static JavaScript and Css files, but not for the images I have uploaded to my site. Also, writing each route for each file gets clunky and I don't think its the best way to serve static files. Here is my code for my app.js file: var express = require('express');
var app = express();
app.use(express.static('CSS'));
app.get('/HTML/index.html',function(req,res) { res.sendFile(__dirname + '/HTML/index.html'); });
app.listen(7888, function() { console.log("If this does not work soon I will kill a small animal"); });
[2:42]
I have tried using the middleware for all of my files at once by creating and putting into a public folder, and then when that didn't work I tried calling the middleware several times caling different directories. No matter what I do, I always get a 404 in the broswer.
1 Answer
Karen Freeman-Smith
29,248 PointsOh no, please don't kill any small animals!
Try this page: https://expressjs.com/en/starter/static-files.html
I think you have to extend the line: app.use(express.static('CSS')); to specify the directory(ies) that have your other files. There are better directions at the site linked above.
Michael Brown
17,651 PointsMichael Brown
17,651 PointsI checked that out, it helped me understand the concepts better but using the code and directions from the website still didn't solve the issue. I have a lot of 404s.
Michael Brown
17,651 PointsMichael Brown
17,651 PointsIt turns out that I needed to name static directory a certain way! But thank you for your help! I had checked out the documentation before and had tried it, but it would not load. It is working now, just have one last bug I need to fix =/