错误node.js无法加载资源

时间:2015-05-09 20:20:40

标签: javascript node.js server

我一直在使用node.js和socket.io,并且遵循教程,但是我一直在从我正在构建的应用程序中收到错误。这是我的server.js文件:

var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function(req, res) {
    file.serve(req, res);
}).listen(1234);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
    function log() {
        var array = [">>> Message from server: "];
        for (var i = 0; i < arguments.length; i++) {
            array.push(arguments[i]);
        }
        socket.emit('log', array);
    }
    socket.on('message', function(message) {
        log('Got message:', message);
        socket.broadcast.emit('message', message);
    });
    socket.on('create or join', function(room) {
        var numClients = io.sockets.clients(room).length;
        log('Room ' + room + ' has ' + numClients + ' client(s)');
        log('Request to create or join room ' + room);
        if (numClients === 0) {
            socket.join(room);
            socket.emit('created', room);
        } else if (numClients === 1) {
            io.sockets.in(room).emit('join', room);
            socket.join(room);
            socket.emit('joined', room);
        } else { // max two clients
            socket.emit('full', room);
        }
        socket.emit('emit(): client ' + socket.id + ' joined room ' + room);
        socket.broadcast.emit('broadcast(): client ' + socket.id + 'joined room' + room);
    });
});

但是当我浏览localhost:1234时,我收到错误Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:1234

1 个答案:

答案 0 :(得分:2)

将index.html放在您的app根文件夹中,它将通过&node-static&#39;提供。作为入口档案。

更简洁的方法是为所有前端文件配置文件夹。

var file = new static.Server('./public');

可以在此处找到完整的节点静态文档:https://www.npmjs.com/package/node-static