User requests some page and I want to know (on server side) what is the language in his/her browser. So I could render template with the right messages.
On clie
You can use req.headers["accept-language"] to get the language/locale the user has set in his browser.
For easier support, you may want to look into a locale module.
You would need to parse the string in req.headers["accept-language"]
. Which will give you a priority list of preferred languages from the client. You can also check req.acceptsLanguages(lang [, ...])
if your language is supported or not.
I would strongly recommend to use express-request-language to do any language matching work, since it could be very difficult to get it right at the first time.
Most of the time, matching a language is not enough. A user might want to change a preferred language. express-request-language
help you store a preferred language in a cookie it also gives your server a URL path to change a preferred language.
All above functionality can be done with just a couple of lines of code:
app.use(requestLanguage({
languages: ['en-US', 'zh-CN'],
cookie: {
name: 'language',
options: { maxAge: 24*3600*1000 },
url: '/languages/{language}'
}
}));
In case of no match, the middleware will also match a default language (en-US
above).
With Express 4.x, you can use the build in req.acceptsLanguages(lang [, ...]) to check if certain languages are accepted.
var express = require('express');
app.get('/translation', function(request, response) {
var lang = request.acceptsLanguages('fr', 'es', 'en');
if (lang) {
console.log('The first accepted of [fr, es, en] is: ' + lang);
...
} else {
console.log('None of [fr, es, en] is accepted');
...
}
});
To get the list of all accepted languages, using Express 4.x, you can use the module accepts.
var express = require('express'), accepts = require('accepts');
app.get('/translation', function(request, response) {
console.log(accepts(request).languages());
...
});
request.acceptsLanguages
will contain a parsed version of request.headers['accept-language']
.
See: http://expressjs.com/en/api.html#req.acceptsLanguages