Node.js,Socket.io:如何获取客户端浏览器语言? [英] Node.js, Socket.io: How to get client browser-language?
问题描述
我正在尝试使用 socket.io 和 node.js 获取用户使用的语言,以便为播放视频提供正确的声音文件.我是node.js和socket.io的初学者.我在客户端使用"navigator.language"获得了该语言,并希望在与socket.io连接/握手时将其发送.
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. I am a total beginner with node.js and socket.io. I got the language on client side with "navigator.language" and wanted to send it when connecting/handshaking to socket.io.
var language = navigator.language;
var socket = io.connect('http://localhost:1337', { query: language });
在服务器端:
io.set('authorization', function(handshakeData, cb) {
console.log(handshakeData.query);
cb(null, true);});
但是我得到的是:
{'en-US': 'undefined', t: '1396002389530'}
我猜第二个属性"t"是已添加的握手ID.但是,如何访问"en-US"?
I guess the second attribute "t" is the handshake ID that has been added. But how do I access 'en-US'?
我的第二种方法是使用模块"locale"( https://github.com/jed/locale ),但是当我使用它时,我总是使用相同的语言,因此我发现它总是可以找到SERVER的语言.我以为我是在新客户端请求页面并发送其HTTP标头时在请求/响应处理程序中使用它的.
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. I thought I use it in the request/response handler, when a new client requests the page and sends its http header.
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.
推荐答案
您快到了.这样做:
var socket = io.connect('http://localhost:1337', { lang: language });
因为查询是保留对象,所以代替了 {query:language}
.
Instead of {query: language}
because query is a reserved object.
您可以通过执行以下操作来访问它:
And you can access this by doing this:
io.set('authorization', function(handshakeData, cb) {
console.log(handshakeData.query.lang);
cb(null, true);});
您也可以这样访问它:
io.sockets.on('connection', function(socket){
console.log(socket.handshake.query.lang);
});
如果您不想将语言变量附加到 query
,则可以通过以下方式访问语言:
If you don't want to append language variable to query
then you can access the language by this:
io.sockets.on('connection', function(socket){
console.log(socket.handshake.headers['accept-language']);
});
这篇关于Node.js,Socket.io:如何获取客户端浏览器语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!