簡體   English   中英

Express 和 i18n 默認語言環境不起作用

[英]Express and i18n default locale not working

我正在嘗試設置 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 加載為默認值,不知何故在 conf 中忽略了 defaultLocale: 'en'。

有任何想法嗎?

提前致謝!

這個庫對我來說有點有趣。 我將此中間件添加到我的快速服務器配置中,並且 i18n 開始正常運行。

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

檢查您的標題: accept-language

根據源代碼,只有經過以下步驟時才會使用defaultLocale

  1. 查詢參數未匹配
  2. 曲奇錯過比賽
  3. headers['accept-language'] 錯過匹配

這個模塊在很多地方尋找語言環境設置。 你有沒有仔細檢查和仔細檢查過這些地方目前都沒有顯示“es”? 也許是您之前進行的測試中的陳舊餅干? 嘗試清除您的 cookie。

這是一個對我有用的解決方案。 我希望網站默認為中文。 我還在導航欄中有 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}`)
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM