Node.js, Socket.io: How to get client browser-language?

余生长醉 提交于 2019-12-10 22:39:48

问题


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 });

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. But how do I access '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. 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.


回答1:


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.

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:

io.sockets.on('connection', function(socket){
  console.log(socket.handshake.headers['accept-language']);
});


来源:https://stackoverflow.com/questions/22710448/node-js-socket-io-how-to-get-client-browser-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!