Learning Node - Express Public folder not working

Tejs picture Tejs · Jun 26, 2014 · Viewed 54.8k times · Source

So I'm new to node and trying to learn how to use the express library with it. However, the problem I'm trying to figure out is why the files in my /public folder do not seem to be served as static content.

Here's my code:

var http = require('http');
var port = process.env.port || 1337;
var express = require('express');
var handlebars = require('express3-handlebars');
var path = require('path');

var application = express();

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

application.engine('handlebars', handlebars({ defaultLayout: 'main' }));

application.get('/', function(req, res){
    res.render('index.handlebars', { someProp: 3 });
});

application.listen(port);

And my directory structure:

/
  - server.js (the above referenced file)
  / Views
    - index.handlebars
    / Layouts
      - main.handlebars
  / public
    - ServeMe.txt

My understanding was that application.use(express.static(path.join(__dirname, 'public'))); was supposed to configure the server to respond to any request under the public folder with that resource if found. What am I doing wrong? Funnily enough, it was easier to configure handlebars as the view engine than to get this public folder working =D

EDIT: The full URL I am trying to request: http://localhost:1337/public/serveme.txt

I've tried case sensitivity (which should be a non-issue), and that also did not work.

Answer

James Allardice picture James Allardice · Jun 26, 2014

The full URL I am trying to request: http://localhost:1337/public/serveme.txt

That's your problem. Anything inside the directory you designate as static content is made available directly from the base URL. You need to request http://localhost:1337/serveme.txt instead.

If you want to only serve static files from /public you can pass a string as the first argument:

application.use("/public", express.static(path.join(__dirname, 'public')));