从 i18next 导出 JSON 到客户端

Export JSON from i18next to the client

我正在尝试将 JSON 语言环境文件从 i18next 导出到 link 作为 API 在客户端上使用。问题是它只导出在“fallbackLng”中指定的语言环境,即 'en'。我怎样才能让它从“detection_options”检测语言环境,以便在 API 上加载和导出正确的语言环境?

// app.js

var detection_options = {
    // order and from where user language should be detected
    order: [/*'path', 'session', */ 'querystring', 'cookie', 'header'],

    // keys or params to lookup language from
    lookupQuerystring: 'lng',
    lookupCookie: 'i18next',
    lookupHeader: 'accept-language',
    lookupSession: 'lng',
    lookupPath: 'lng',
    lookupFromPathIndex: 0,

    // cache user language
    caches: false,
}

// i18next configuration
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const middleware = require('i18next-http-middleware');
i18next.use(Backend)
    .use(middleware.LanguageDetector)
    .init({
        debug: true, // debug option shows that "zh-hant" is loaded correctly when the Chinese site is accessed.
        detection: detection_options,
        fallbackLng: ['en', 'zh'],
        backend: {
            loadPath(lng, ns) {
                if (lng === 'zh' || lng === 'zh-HK' || lng === 'zh-TW') {
                    return path.join(__dirname, 'locales/zh-hant.json');
                } else if (lng === 'en-US') {
                    return path.join(__dirname, 'locales/en.json');
                }
                return path.join(__dirname, 'locales/{{lng}}.json');
            }
        }
    })
app.use(middleware.handle(i18next));

const localeController = require('../controllers/locale');
app.get('/locale', localeController.getLocale);
// locale.js
exports.getLocale = async (req, res, next) => {
    var i18next = require('i18next');
    res.status(200).json(
        i18next.t('tree', { returnObjects: true })
    )
}

使用请求对象中的 t 函数,例如:

https://github.com/i18next/i18next-http-middleware/issues/51#issuecomment-1094851968