Ole*_*ats 43 javascript node.js express
用户请求某个页面,我想知道(在服务器端)他/她的浏览器中的语言是什么.所以我可以使用正确的消息渲染模板.
在客户端,它很容易:
var language = window.navigator.userLanguage || window.navigator.language
Run Code Online (Sandbox Code Playgroud)
Joa*_*son 69
您可以使用req.headers ["accept-language"]来获取用户在其浏览器中设置的语言/区域设置.
为了便于支持,您可能需要查看区域设置模块.
小智 25
request.acceptsLanguages将包含解析版本request.headers['accept-language'].
请参阅:http://expressjs.com/en/api.html#req.acceptsLanguages
jgr*_*cha 24
使用Express 4.x,您可以使用req.acceptsLanguages(lang [,...])中的构建来检查是否接受某些语言.
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');
...
}
});
Run Code Online (Sandbox Code Playgroud)
要使用Express 4.x获取所有可接受语言的列表,您可以使用该模块接受.
var express = require('express'), accepts = require('accepts');
app.get('/translation', function(request, response) {
console.log(accepts(request).languages());
...
});
Run Code Online (Sandbox Code Playgroud)
用于设置请求语言并全局使用它的中间件:
\n// place this middleware before declaring any routes\napp.use((req, res, next) => {\n // This reads the accept-language header\n // and returns the language if found or false if not\n const lang = req.acceptsLanguages('bg', 'en')\n \n if (lang) { // if found, attach it as property to the request\n req.lang = lang\n } else { // else set the default language\n req.lang = 'en'\n }\n\n next()\n})\nRun Code Online (Sandbox Code Playgroud)\n现在您可以访问“req.lang”
\napp.get('/', (req, res) => {\n res.send(`The request language is '${req.lang}'`)\n})\nRun Code Online (Sandbox Code Playgroud)\n使用翻译的示例
\nconst translate = {\n en: {\n helloWorld: "Hello World!"\n },\n bg: {\n helloWorld: "\xd0\x97\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb2\xd0\xb5\xd0\xb9 \xd0\xa1\xd0\xb2\xd1\x8f\xd1\x82!"\n }\n}\napp.get('/hello-world', (req, res) => {\n res.send(translate[req.lang].helloWorld)\n})\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
40722 次 |
| 最近记录: |