我正在使用 Express 和 socket.io 编写应用程序,但我的服务器找不到静态文件在哪里。我意识到这个问题已经被问过多次,但所提出的解决方案都不适合我。我尝试了不同的方法来使用 express.static()
引用公共(public)文件夹或重新排列代码结构,但仍然没有成功。
代码结构:
/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
关于javascript - Express 服务器不提供静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35229973/