[英]Node.js, Socket.io: How to get client browser-language?
I am trying to get the language the user uses in order to serve the right sound files for a playing video, using socket.io and node.js. 我正在尝试使用socket.io和node.js来获取用户使用的语言,以便为播放的视频提供正确的声音文件。 I am a total beginner with node.js and socket.io.
我是node.js和socket.io的初学者。 I got the language on client side with "navigator.language" and wanted to send it when connecting/handshaking to socket.io.
我在客户端使用“ navigator.language”获得了该语言,并希望在与socket.io连接/握手时将其发送。
var language = navigator.language;
var socket = io.connect('http://localhost:1337', { query: language });
And on server-side: 在服务器端:
io.set('authorization', function(handshakeData, cb) {
console.log(handshakeData.query);
cb(null, true);});
But what I get is: 但是我得到的是:
{'en-US': 'undefined', t: '1396002389530'}
I guess the second attribute "t" is the handshake ID that has been added. 我猜第二个属性“ t”是已添加的握手ID。 But how do I access 'en-US'?
但是,如何访问“ en-US”?
My second approach was to use the module "locale" ( https://github.com/jed/locale ), but when I used that, I always got the same language, so I figured that it always finds the SERVER's language. 我的第二种方法是使用模块“ locale”( https://github.com/jed/locale ),但是当我使用它时,我总是使用相同的语言,因此我发现它总是可以找到SERVER的语言。 I thought I use it in the request/response handler, when a new client requests the page and sends its http header.
我以为我是在新客户端请求页面并发送其HTTP标头时在请求/响应处理程序中使用它的。
var handler = function(req, res) {
lang = new locale.Locales(req.headers["accept-language"]);
lang=lang.best(supported);
console.log(pf);
}
I hope you get what I am trying to do and maybe know a better solution. 我希望您能得到我正在尝试做的事情,并且也许知道更好的解决方案。 Thank you in advance.
先感谢您。
You're almost there. 你快到了。 Do this:
做这个:
var socket = io.connect('http://localhost:1337', { lang: language });
Instead of {query: language}
because query is a reserved object. 而不是
{query: language}
因为query是保留对象。
And you can access this by doing this: 您可以通过执行以下操作来访问它:
io.set('authorization', function(handshakeData, cb) {
console.log(handshakeData.query.lang);
cb(null, true);});
You can also access it like this: 您也可以像这样访问它:
io.sockets.on('connection', function(socket){
console.log(socket.handshake.query.lang);
});
If you don't want to append language variable to query
then you can access the language by this: 如果您不想在
query
后附加语言变量,则可以通过以下方式访问语言:
io.sockets.on('connection', function(socket){
console.log(socket.handshake.headers['accept-language']);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.