Jamie Jordan Jamie Jordan - 5 months ago 28
Javascript Question

Access req property outside of route endpoints

var express = require('express');
var router = module.exports = express.Router();
var server = require("http").Server(express);
var io = require("socket.io")(server);
server.listen(5000);

//how to get my user.id here?


router.get('/', function(req, res) {

io.on('connection', function(client) {
client.on('order_'+req.user.id, function(data) {
io.emit('order_'+req.user.id,data);
});
});

});


Above code worked well, but it has a problem. The connection get multiplied if the user refresh the page / or reenter the page. I should have put outside of the
router.get('/'..
but I have to use
req.user.id
.

Any idea how can I get user.id ??

Answer

As I already mentioned you don't need to handle this, because on refresh client closes old connection and new page load should connect once more, so there are no multiple connections.

My Sample

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

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

io.on('connection', function(socket){
    console.log('CONNECTED!');

    socket.on('disconnect', function () {
        console.log('DISCONNECTED!');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

Just refresh few times tab and you will get following output on server:

CONNECTED!
DISCONNECTED!
CONNECTED!
DISCONNECTED!
CONNECTED!
...

Passing user id

Anyway this should be done by passing user id information from client to server and you can do it by defining new event for it, like authenticated

socket.on('authenticated', function(userId) {
    socket.on('disconnect', function () {
        console.log(userId + ' DISCONNECTED!');
    });
});

Or pass it with every event as additional data.

socket.on('someEvent', function(someData, userId) {
    //...
});

alternative could be using module like session.socket.io

sessionSockets.on('connection', function (err, socket, session) {
    //your regular socket.io code goes here
    //and you can still use your io object
});

Emit events from routes

In order to emit events from routes you need have some kind of connection between express and socket.io, that could be done by having mapping like this:

var sockets = {};
socket.on('authenticated', function(userId) {
    sockets[userId] = socket; 
    ...
});

and inside routes just use sockets[userId].emit to emit events.

Reference

Comments