Express和i18n默认语言环境不起作用

时间:2015-02-12 14:26:30

标签: node.js express i18n-node

我试图设置i18n-node和Expressjs。我的担心是:

// 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个语言环境,我可以在它们之间切换没问题,但是表达总是加载es.json作为默认值,不知何故忽略了defaultLocale:' en'在conf。

任何想法?

提前致谢!

4 个答案:

答案 0 :(得分:2)

检查标题:accept-language

根据source codedefaultLocale仅在执行以下步骤时使用:

  1. queryParameter缺少匹配项
  2. Cookie Miss Match
  3. headers ['accept-language']错过比赛

答案 1 :(得分:0)

此模块在lot of places中查找区域设置。您是否仔细检查并仔细检查过这些地方当中没有任何地方显示“es”?也许你之前测试过的陈旧曲奇饼干?尝试清除您的Cookie。

答案 2 :(得分:0)

这个库对我来说有点有趣。我将此中间件添加到我的快速服务器配置中,并且i18n开始发挥应有的作用。

app.use(function (req, res, next) {
    var locale = 'en'
    req.setLocale(locale)
    res.locals.language = locale
    next()
})

答案 3 :(得分: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}`)
);