[英]To access request parameter in socket.on function
I'am beginner of node.js,Sorry if I went wrong. 我是node.js的初学者,很抱歉,如果我做错了。
To get the parameter passed in URL like localhost:3000?id=man&fm=gilli I used 为了获得在URL中传递的参数,例如localhost:3000?id = man&fm = gilli,我使用了
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 我的疑问是我想在socket.on函数中访问fm,为此我已经尝试过
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. 这里的条件是我们不应该将fm参数存储在全局变量中,这意味着我们必须直接访问io.socket函数中url中传递的参数。
ie:In the below code fm should not be accessed like id parameter. ie:在下面的代码中,不应像id参数一样访问fm。
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.');
}
});
});
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.
在Express中,当套接字连接时,默认情况下我们不知道它属于哪个会话,这意味着我们无法对该连接进行任何私有操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.