2

我正在尝试设置 i18n-node 和 Expressjs。我的conf是这样的:

// i18n 配置 =============================================== ===========

var i18nconf = {
   locales        : ["en", "es"],
   cookie         : "locale",
   defaultLocale : "en",
   directory      : path.join(__dirname, "lang"),
   indent : "  "
};

i18n.configure(i18nconf);
app.use(i18n.init);

lang/ 文件夹 en.json 和 es.json 上有 2 个语言环境,我可以在它们之间切换没问题,但 express 总是默认加载 es.json,不知何故忽略了 conf 中的 defaultLocale: 'en'。

有任何想法吗?

提前致谢!

4

4 回答 4

2

这个库对我来说有点有趣。我将此中间件添加到我的快速服务器配置中,并且 i18n 开始正常运行。

app.use(function (req, res, next) {
    var locale = 'en'
    req.setLocale(locale)
    res.locals.language = locale
    next()
})
于 2018-06-27T08:17:01.790 回答
2

检查您的标题:accept-language.

根据源代码defaultLocale只有在以下步骤完成时才会使用:

  1. 查询参数未匹配
  2. cookie 未匹配
  3. headers['accept-language'] 错过匹配
于 2018-10-03T17:41:18.090 回答
0

这个模块在很多地方寻找区域设置。您是否仔细检查并仔细检查了这些地方目前都没有指示“es”?也许是您之前测试的陈旧饼干?尝试清除您的 cookie。

于 2015-02-12T15:14:21.910 回答
0

这是一个适合我的解决方案。我希望网站默认为中文。我在导航栏中也有 2 个语言更改按钮(标志图像),它们转到 /en 和 /zh 路由,它们设置 cookie 并将用户重定向回他们来自的页面。

使用隐身窗口和清除 cookie 并刷新站点对其进行了测试。首先在 ZH 中加载,然后通过添加/更改 cookie 值来更改语言。

我还必须在中间件中使用 req.setLocale() 之前初始化 i18n。

const express = require('express');
const hbs = require('express-hbs');
const i18n = require('i18n');
const app = express();
const cookieParser = require('cookie-parser');

const indexRoutes = require('./routes/indexRoutes');

app.engine(
  'hbs',
  hbs.express4({
    partialsDir: __dirname + '/views/partials/',
    helpers: {
      __: function () {
        return i18n.__.apply(this, arguments);
      },
      __n: function () {
        return i18n.__n.apply(this, arguments);
      },
    },
  })
);

app.set('view engine', 'hbs');

app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));

i18n.configure({
  locales: ['zh', 'en'],
  defaultLocale: 'zh',
  cookie: 'locale',
  directory: __dirname + '/locales',
  directoryPermissions: '755',
  autoReload: true,
  updateFiles: true,
  objectNotation: true,
  api: {
    __: '__', //now req.__ becomes req.__
    __n: '__n', //and req.__n can be called as req.__n
  },
});
app.use(i18n.init);

app.use((req, res, next) => {
  if (req.cookies.locale === undefined) {
    res.cookie('locale', 'zh', { maxAge: 900000, httpOnly: true });
    req.setLocale('zh');
  }

  next();
});

app.get('/zh', (req, res) => {
  res.cookie('locale', 'zh', { maxAge: 900000, httpOnly: true });
  res.redirect('back');
});

app.get('/en', (req, res) => {
  res.cookie('locale', 'en', { maxAge: 900000, httpOnly: true });
  res.redirect('back');
});

app.use('/', indexRoutes);

app.listen(process.env.PORT || 3000, () =>
  console.log(`Server up on ${process.env.PORT || 3000}`)
);
于 2020-04-09T09:29:25.283 回答