Question

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>
Was it helpful?

Solution

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

OTHER TIPS

Express is a framework that amongst other stuff replaces the 'http' module. You appear to be trying to use both together. Try this:

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

Credit to Ben for the nudge on the get method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top