8

I have something along the lines of the following:

var request = require('request'),
    express = require('express');

var app = express.createServer();

var port = process.env.PORT || 8080;

app.configure(function(){
    app.set("view options", { layout: false, pretty: true });
    app.use(express.favicon());
    app.use("/public", express.static(__dirname + '/public'));
    }
);

app.listen(port);

// Routes
app.get('/', function(req, resp){
    resp.render('index.jade', {pageTitle: 'Some title'});
});

Yet, when I visit /public/myfile.css for example, I still get:

Cannot GET /public/myfile.css My index.jade templates cannot seem to call the files either

Why is this?

Alex
  • 37,502
  • 51
  • 204
  • 332

3 Answers3

15

I don't think supplying the path like that is supported:

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

Try this, and look for your public files in the root:

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

So /public/myfile.css becomes /myfile.css.

Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
  • but is there a way to force the /public bit to still work? My app uses whatever is after the / as a parameter for the main route... so, its stuck in a loop at the moment – Alex Mar 10 '12 at 16:22
  • 1
    So put a `public` directory in your `public` directory, or mount your routes after static. – Linus Thiel Mar 10 '12 at 23:21
  • 24
    This answer is wrong. `app.use("/public", express.static(__dirname + '/public'));` is supported. Checkout the app.use definition: https://github.com/senchalabs/connect/blob/master/lib/proto.js#L61 Something else was broken. – ibash Aug 23 '12 at 03:06
1

Important also is where the position of the app.use(express.static(__dirname + '/public')) statement...

I had a problem when it was nor working when I've accidentally put this in a ./middle-conf.js file which later was imported as var configure = require('./middle-conf) and then the express app was passed into this configure(app).

So the express middle-ware processing order was not not correctly working.

Viliam
  • 300
  • 5
  • 11
0

this works fine...

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

and in your html pages access it like this..

<script src="/public/yourcodes.js"></script>
cabs
  • 710
  • 7
  • 14