【问题标题】:Express server not serving static filesExpress 服务器不提供静态文件
【发布时间】:2016-02-05 17:23:31
【问题描述】:

我正在使用 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
})

【问题讨论】:

    标签: javascript node.js sockets express


    【解决方案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
    

    【讨论】:

    • 谢谢!我尝试了“./public/html”,但并没有真正起作用。所以我把 index.html 移到 public 的根目录下,尝试了“./public”,还是不行。这里可能会发生什么?
    • 我已经更新了答案。对于我的解决方案中的错误,我深表歉意。
    • 奇迹般地工作......非常感谢!
    最近更新 更多