user1426594
user1426594

Reputation: 125

Why is Express not serving up my static files?

URL: http://example.com:8080/js/file.js

var express = require('express');
app = express();
app.use(express.static('public'));
app.listen(8080);

Directory Structure

/

index.js (loaded node file)
public (folder)
----js (folder)
    ----file.js (requested file)

Error: Cannot GET /js/file.js

Upvotes: 1

Views: 954

Answers (3)

LDJ
LDJ

Reputation: 7304

What version of express are you using? For me, using 3.4.0, the following didn't work:

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

but this did:

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

Not sure if its version specific, but usign the first syntax if was failing with the same Error: Cannot get XXX error

Upvotes: 0

Mike DeMille
Mike DeMille

Reputation: 441

It might be easier to set up something like what is described in this tutorial

http://www.mfranc.com/node-js/node-js-simple-web-server-with-express/

/* serves all the static files */
app.get(/^(.+)$/, function(req, res){ 
    console.log('static file request : ' + req.params);
    res.sendfile( __dirname + req.params[0]); 
});

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311835

Provide the full path to the directory:

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

Upvotes: 2

Related Questions