Svetan Dimoff Svetan Dimoff - 6 months ago 30
Node.js Question

NodeJS won't serve my static files

I encountered a lot of instances of my problem, however none of them worked for me. Where is my server root, if both of these paths don't work? Static files aren't found neither under

la-wars
>
public
>
css
>
file
, nor under the more relative
public
>
css
>
file
.

This is how I use express for the purpose:

app.use(express.static(path.join(__dirname, 'public')));


And it results in the second 404 result below. With the first one, I had
express.static()
commented out and tried an absolute path in the markup.

enter image description here

enter image description here

EDIT: The entire entry point app:

var express = require('express'),
app = require('express')(),
ejs = require('ejs'),
path = require('path'),
cookieParser = require('cookie-parser'),
util = require('util'),
port = process.env.PORT || 3000,
user = require('./models/user.js'),
formidable = require('formidable'),
router = express.Router();

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(require('.middleware/auth.js'));

app.use(require('./routes')(express));

app.listen(port);

Answer

It depends what the url is you put on your html pages, but from the console's error window, I'm going to guess this (notice extra first argument) solves your problem:

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

It seems you use both "/public" (for the js) and "public" (for the css) in your html file. The code above should at least fix one of the two errors.

The call:

app.use(express.static(path.join(__dirname, 'public')));

is saying that it could serve your files in the 'public' folder directly, so you can keep this but in the html files remove the "public/" from the urls and begin them with "/" directly.