繁体   English   中英

Express服务器不提供静态文件

[英]Express server not serving static files

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

您需要提供包含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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM