Node.js,express,socket.io app连接错误

时间:2014-05-04 14:32:28

标签: javascript node.js express socket.io

我有一个简单的应用程序,它使用socket.io模块作为node.js. 当我使用node express_server.js命令运行我的服务器时它可以正常工作,但是当我想在浏览器中打开我的http://localhost:8080页面时,节点会抛出错误:

 /home/tomek/dev/node/node_modules/express/lib/application.js:119
  this._router.handle(req, res, function(err) {
              ^
TypeError: Cannot read property 'handle' of undefined
    at Function.app.handle (/home/tomek/dev/node/node_modules/express/lib/application.js:119:15)
    at Server.app (/home/tomek/dev/node/node_modules/express/lib/express.js:28:9)
    at Manager.handleRequest (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:565:28)
    at Server.<anonymous> (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:119:10)
    at Server.EventEmitter.emit (events.js:110:17)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:504:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
    at Socket.socketOnData (_http_server.js:357:22)
    at Socket.EventEmitter.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:156:16)

我的express_server.js文件如下:

var express = require('express'),
    socket = require('socket.io'),
    http = require ('http');

var app = express();
server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);



io.sockets.on('connection', function (client) {
    console.log('-- Client connected --');
});

和index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat application</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
    var server = io.connect('http://localhost:8080');
</script>   
</body>
</html>

2 个答案:

答案 0 :(得分:2)

没有定义路由器。尝试在创建应用程序后添加此内容(var app = express()):

app.get('/', function(req, res) {
    // res.send('hello world');
    res.sendfile('index.html');
});

答案 1 :(得分:0)

Express是一个框架,除了其他东西之外,它取代了'http'模块。您似乎试图将两者结合使用。试试这个:

var express = require('express'),
var app = express();

app.get('/', function(req, res) {
  res.sendfile('index.html');
});

var port = Number(process.env.PORT || 8080);
app.listen(port, function() {
  console.log("Listening on " + port);
});

感谢Ben对get方法的推动。