Manohar Gunturu
Manohar Gunturu

Reputation: 125

To access request parameter in socket.on function

I'am beginner of node.js,Sorry if I went wrong.

To get the parameter passed in URL like localhost:3000?id=man&fm=gilli I used

   app.get('/',function(req, res){
     var now = req.query.id;

     res.sendfile(__dirname + '/index.html');

   });

My doubt is I want to access fm in socket.on function,for that I have tried like this

            io.sockets.on('connection',function(socket){

                socket.nickname = req.query.fm;   //here I accessed it  
            users[socket.nickname] = socket;

        });

But it getting error that:

        req is not defined.

A condition here is we should not store fm parameter in global variable,Means we have to directly access the parameter passed in url in io.socket function.

i.e:In the below code fm should not be accessed like id parameter.

My total code is:

    var express = require('express'),
    app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongoose = require('mongoose'),
    users = {},
now,
other;

    server.listen(3000);





        app.get('/',function(req, res){
             now = req.query.id;

             res.sendfile(__dirname + '/index.html');

        });   

       io.sockets.on('connection',function(socket){

              socket.nickname = now; // parameter id stored here using a global variable

               users[socket.nickname] = socket;





socket.on('send message',function(data, callback){
    var msg = data;


         var name = req.query.fm;    //here I got error
         var msg = msg;
         if(name in users){

                 }else{
         callback('Error enter a valid user.');
         }

  });

});

Upvotes: 1

Views: 1668

Answers (1)

Matthias Holdorf
Matthias Holdorf

Reputation: 1050

You need to implement an authorization.

In Express, when a socket connects, we don’t know which session it belongs to by default, meaning we can’t do anything private with that connection.

Upvotes: 2

Related Questions