无法通过 FETCH 后端让 react-i18next 读取 JSON 文件

IT技术 reactjs i18next create-react-app react-i18next
2021-04-30 06:56:45

我正在尝试react-i18next在客户端上使用i18next-fetch-backend,即使我可以通过浏览器访问 JSON 翻译文件,但在init例程中处理它们的方式有些麻烦

作为记录,我将使用create-react-app作为前端 React 应用程序的基础,如果这有所作为,到目前为止我所有的测试都在 localhost 中(在 localhost:3000 上使用 React 应用程序,“服务器”在本地主机上:8000)。

这是我的初始化文件:

import i18n from 'i18next';

import LanguageDetector from 'i18next-browser-languagedetector';
import Cache from 'i18next-localstorage-cache';
import Fetch from 'i18next-fetch-backend';

i18n
  .use(LanguageDetector)
  .use(Cache)
  .use(Fetch)
  .init({
    fallbackLng: 'en', 
    ns: ['common','app'],
    defaultNS: 'common',
    preload: ['en'], 
    wait: true,
    backend: {
      loadPath: 'http://localhost:8000/static/locales/{{lng}}/{{ns}}.json',
      addPath: 'http://localhost:8000/static/locales/{{lng}}/{{ns}}',
      parse: function (data) { console.log("DATA", data) },
      init: {
        mode: 'no-cors',
        credentials: 'include',
        cache: 'default'
      }
    },

    cache: {
      enabled: true,
      prefix: 'i18next_translations_',
      expirationTime: 24*60*60*1000 //one day
    },

    debug: true,

    detection: {
      order: ['localStorage', 'cookie'], 
      lookupCookie: 'i18nextLng',
      lookupLocalStorage: 'i18nextLng',
      caches: ["localStorage"] 
      //cookieMinutes: 10 // if we want the cookie to expire
    },

  });

export default i18n;

...然后包装我的应用程序的组件如下所示:

import React, { Component } from 'react';

import { I18nextProvider } from 'react-i18next'
import i18n from './i18n' // the init code from above

export default class Localize extends Component {
  render () {
    return (
      <I18nextProvider i18n={i18n}>
        {this.props.children}
      </I18nextProvider>
    )
  }
}

...最后,翻译应该发生的组件:

class TestTranslate extends Component {

  render () {
    const { t } = this.props;
    return (
      <div>
          {t('key1')}
          {t('key3')}
      </div>
    )
  }
}

export default translate()(LearnHome)

如果我在加载页面时查看 Chrome 调试器,我会看到以下内容: Chrome 控制台

执行两个 FETCH 命令:一个 forcommon.json和一个 for app.json在我看来,确实看起来两个 FETCH 命令都正确执行,但是根本没有数据使其成为init 配置数据中parse()函数backend

事实上,如果我弹出 Chrome 网络选项卡,浏览器肯定会认为数据已从服务器正确返回到浏览器:

Chrome 网络标签

所以我对正在发生的事情感到困惑。我已经仔细阅读了 i18next 文档和几个示例,但到目前为止都是空的。任何帮助表示赞赏。

谢谢!

1个回答

好的,我想通了。它与 i18next 无关。我们正在 Vagrant 实例中运行一个 Django 内置开发 Web 服务器,用于本地开发。默认情况下,Django 的 Web 服务器不会在静态文件返回给客户端时将标头放在它们上。我的本地客户端环境 ( localhost:3000) 实质上是向我的本地 Django 环境 ( localhost:8000)发出 CORS 请求,因此我们必须重新配置我们的开发 Django 服务器以在静态文件请求上返回 CORS 标头。