这可能会因为服务器端没有正确获取客户端的语言设定,而默认回退到备用语言。要解决这个问题,可以在客户端代码中添加以下代码段:
import i18next from 'i18next';
import i18nextMiddleware from 'i18next-http-middleware';
import i18nextBackend from 'i18next-node-fs-backend';
const i18n = i18next.createInstance();
i18n.use(i18nextMiddleware.LanguageDetector).use(i18nextBackend).init({
fallbackLng: 'en',
backend: {
loadPath: 'locales/{{lng}}/{{ns}}.json',
addPath: 'locales/{{lng}}/{{ns}}.missing.json',
},
});
app.use(i18nextMiddleware.handle(i18n, {
ignoreRoutes: ['/foo'],
removeLngFromUrl: false,
}));
i18n.on('languageChanged', (lng) => {
console.log(`Language changed to ${lng}`);
});
这里的关键是使用i18nextMiddleware.LanguageDetector()来处理客户端语言设置,确保服务器能够正确识别客户端的语言并使用对应的翻译文件。同时,使用i18nextMiddleware.handle()将i18n对象中的语言设置传递给应用程序,确保后续的翻译代码能够正确的获取当前语言设定,避免默认回退到备用语言。