express.js中的多语言路由? [英] Multi-language routes in express.js?
本文介绍了express.js中的多语言路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一个关于在express.js中实现多语言路由的最佳实践示例.我想使用accept-language
标头获取浏览器语言,然后自动重定向到相应的语言路线,例如
I'm wondering if there is a best practise example on how to implement multi-lanuage routes in express.js. i want to use the accept-language
header to get the browser language and then redirect automatically to the corresponding language route like
www.foo.bar/de/startseite
或
www.foo.bar/en/home
对此有何建议?
推荐答案
我完成了以下操作: 安装i18n-node modul并在express js中注册.这是代码.
i have done the following: install i18n-node modul and register in the express js. here is code.
var express = require('express')
, routes = require('./routes')
, http = require('http')
, i18n = require("i18n");
var app = express();
i18n.configure({
// setup some locales - other locales default to en silently
locales:['de', 'en'],
// disable locale file updates
updateFiles: false
});
app.configure(function(){
...
app.use(i18n.init);
...
});
// register helpers for use in templates
app.locals({
__i: i18n.__,
__n: i18n.__n
});
在此之后设置以下内容以获取所有请求
after this set the following to get all request
// invoked before each action
app.all('*', function(req, res, next) {
// set locale
var rxLocal = /^\/(de|en)/i;
if(rxLocal.test(req.url)){
var arr = rxLocal.exec(req.url);
var local=arr[1];
i18n.setLocale(local);
} else {
i18n.setLocale('de');
}
// add extra logic
next();
});
app.get(/\/(de|en)\/login/i, routes.login);
也许有帮助.
这篇关于express.js中的多语言路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文