Node.js 可选的语言环境参数expressjs
我想在我的url中执行一个可选的区域设置参数,如下所示:Node.js 可选的语言环境参数expressjs,node.js,express,internationalization,Node.js,Express,Internationalization,我想在我的url中执行一个可选的区域设置参数,如下所示: app.use("/:locale?/", routes.Index); // Internationalization app.use(i18n.init); app.use(localeRedirection(supportedLocales, defaultLocale)); domain.tld/=>受支持的最佳语言环境 domain.tld/fr/=>强制“fr”作为区域设置 所以,我做了这样的事情: app.use("
app.use("/:locale?/", routes.Index);
// Internationalization
app.use(i18n.init);
app.use(localeRedirection(supportedLocales, defaultLocale));
- domain.tld/=>受支持的最佳语言环境
- domain.tld/fr/=>强制“fr”作为区域设置
app.use("/:locale?/", routes.Index);
// Internationalization
app.use(i18n.init);
app.use(localeRedirection(supportedLocales, defaultLocale));
但是我在尝试获取domain.tld/register/时遇到了一个问题,因为“register”被认为是所请求的区域设置
有人有这样做的想法吗
谢谢。如果有人想知道我做了什么,这是我的express中间件:
"use strict";
var locale = require("locale");
module.exports = function (supportedLanguages, defaultLocale) {
// Creation of the list of supported locales
var supportedLocales = new locale.Locales(supportedLanguages);
locale.Locale.default = defaultLocale;
return function (req, res, next) {
var matches,
askedLocale = null,
bestLocale = null,
locales = null,
url = null;
// Test if locale in url
matches = req.url.match(/^\/([a-zA-Z]{2})([\/\?].*)?$/i);
// If locale defined in url
if (matches !== null) {
// Get locale
askedLocale = matches[1].toLowerCase();
// Modify url for express logic
req.url = matches[2] || '/';
}
// If the asked locale is supported
if (askedLocale !== null && supportedLanguages.indexOf(askedLocale) !== -1) {
locales = new locale.Locales(askedLocale);
} else {
// Get locale from headers
locales = new locale.Locales(req.headers["accept-language"]);
}
// Getting the best supported locale
bestLocale = locales.best(supportedLocales).toString();
// If the asked locale is not the best supported
if (askedLocale !== null && askedLocale !== bestLocale) {
// Creation of the new url
url = "https://" + req.headers.host + "/" + bestLocale + req.url;
// Redirection to the new locale
res.redirect(302, url);
} else {
// Else if already best locale
req.setLocale(bestLocale);
res.locals.locale = req.getLocale();
// Continue
next();
}
};
};
我这样称呼它:
app.use("/:locale?/", routes.Index);
// Internationalization
app.use(i18n.init);
app.use(localeRedirection(supportedLocales, defaultLocale));
将“supportedLocales”作为区域设置数组,将“defaultLocale”作为默认区域设置。的可能重复项是否表示完全重复。。。我来试试这个解决方案。好的,它很有效。我对express是个新手,不知道修改req.url会影响express路由。