Ajeesh Ajeesh - 6 months ago 22
Javascript Question

Emitted value cannot be added to DIV express.js socket.io

I have the following app.js

var express = require('express');
var app = express();
// var responseHandlerRouter = require('./routes/responseHandlerRouter.js');

routes = require('./routes');

var server = app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

io = require('/usr/local/lib/node_modules/socket.io').listen(server);

app.use('/', routes(io));


routes.js

var express = require('express');
var router = express.Router();

module.exports = function (io) {

// all of this router's configurations

router.get('/login', function (req, res, next) {
io.emit('notification', 'news');
res.end('well finally I am here');
});

return router;

}


index.html

<!doctype html>
<html>
<head>
<script src="http://127.0.0.1:3000/socket.io/socket.io.js"></script>
<script>

var socket = io.connect('http://localhost:3000/login');

socket.on('notification', function (data) {
console.log(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>


When I do a get on the URL, it should emit but its not happening. Its not showing any errors, but fails silently.

Is there anything wrong?

Update

"news" was being sent from the router successfully.

I want to show the "news" in the div.
but I am not able to append this as follows

.... socket.on('notification', function (data) {
$('#messages').html(data);
});
</script>
</head>
<body>
<ul id='messages'></ul>
</body>....


Will make this eligible for bounty

Answer

Looks like you are using a router in a wrong way.

Not sure, but I think that app.use('/login', routes(io)) instead of what you've got should do the trick.

In your implementation your router receives only GETs to '/'

EDIT: although the answer is accepted, the real solution is in the comments below (wrong connection url specified)

Comments