Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

javascript - Node.js, express, socket.io app connection error

I've got a simple app which uses socket.io module for node.js. When i run my server with node express_server.js command it works ok, but when i want to open my http://localhost:8080 page in browser, node throws an error:

 /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)

My express_server.js file looks like:

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 --');
});

and 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no router defined. Try add this after creating the app (var app = express()):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...