1

Using the following simple Node server

var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root
app.listen(3000);
console.log('Listening on port 3000');

I have of course put a 'public' directory in my root and also dropped a index.html file in it but when i point my browser to

http://localhost:3000/public/

I get

Cannot GET /public/

Bachalo
  • 6,965
  • 27
  • 95
  • 189
  • possible duplicate of [Express-js can't GET my static files, why?](http://stackoverflow.com/questions/5924072/express-js-cant-get-my-static-files-why) – Leonid Beschastny Feb 04 '15 at 17:35

2 Answers2

0

This one caught me out as well when starting with express.

http://localhost:3000/public/ won't be accessible.

For example lets say you have a css folder inside of the public directory with a file called styles.css

Your browser would be able to access that file at http://localhost:3000/css/styles.css.

The express documentation on express.static can be found here: app.use (under the two example tables)

edit 1: See this answer here.

edit 2: @Leonid Beschastny answer is correct, I didn't see that a path to a folder was missing in app.use(express.static(path.join(__dirname, 'public')));

Community
  • 1
  • 1
Matt
  • 13
  • 4
0

The problem is how you're mounting express.static middleware. In your example you're mounting it to the root of your application.

So, in your example you should be able to access content of /public directory from http://localhost:3000/.

So, all you need is to specify a mounting point for express.static middleware:

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

You should also keep in mind that express.static don't have a default index page. So, if you have no index.html in your public directory you'll get 404 anyway (express.static won't list your files like apache do).

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122