HoneyWine
HoneyWine

Reputation: 187

Express server not serving static files

I'm using Express and socket.io to write an app, but my server can't find where the static files are. I realize this question has been asked multiple times, but none of the proposed solutions worked for me. I've tried different ways to reference the public folder with express.static() or to rearrange the code structure, but still no luck.

Code structure:

/node_modules
/public
    /css
        index.css
    /html
        index.html
    /js
/src
    /server
        /models
index.js
package.json

index.js:

// Get all modules needed
var express         = require('express'),
    http             = require('http'),
    bodyParser      = require('body-parser'),
    logger          = require('logger'),
    mongoose        = require('mongoose'),
    io              = require('socket.io'),
    path            = require('path'),
    methodOverride = require('method-override'),
    User = require('./src/server/models/user');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/' + name);
var db = mongoose.connection;*/
var uristring =
    process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    'mongodb://localhost/HelloMongoose';

mongoose.connect(uristring, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: ' + uristring + '. ' + err);
    } else {
        console.log ('Succeeded connected to: ' + uristring);
    }
});

// Set up
var app = express();
var server = http.Server(app);
var ioServer = io(server);
app.use(bodyParser.json({}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(bodyParser());

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

// Connect to a socket
ioServer.on('connection', function(socket){
    // do something
})

Upvotes: 0

Views: 434

Answers (1)

gnerkus
gnerkus

Reputation: 12019

You'll need to serve the directory that contains the index.html file:

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

You need to ensure the route specified is /public/html and not ./public/html.

While this solves the problem, I'll recommend you place the index.html file at the root of your public directory. This is the recommended code structure:

/node_modules
/public
    /css
        index.css
    /js
    index.html
/src
    /server
        /models
index.js
package.json

Upvotes: 1

Related Questions