Express服务器不提供静态文件

时间:2016-02-05 17:23:31

标签: javascript node.js sockets express

我正在使用Express和socket.io编写应用程序,但我的服务器无法找到静态文件的位置。我意识到这个问题已被多次询问,但所提议的解决方案都没有对我有用。我尝试过使用express.static()引用公用文件夹的不同方法,或重新排列代码结构,但仍然没有运气。

代码结构:

/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
})

1 个答案:

答案 0 :(得分:1)

您需要提供包含index.html文件的目录:

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

您需要确保指定的路线为/public/html而非./public/html

虽然这解决了问题,但我建议您将index.html文件放在public目录的根目录下。这是推荐的代码结构:

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