NodeJS won't serve static files, even when using express.static

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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.

Solution 3

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>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply