0

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>

2 Answers 2

2

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');
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1 ed, slight adjustment. res.sendfile('index.html');
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.