从花药后端端点加载资源文件

时间:2020-07-02 09:21:17

标签: reactjs local i18next react-i18next

我添加了i18nex来响应项目,我想从另一个域服务器(例如,托管在“ http://xxxx.com”中的项目)加载资源文件,然后将文件本地添加到项目的公共文件中,然后使用loadPath:'/locales/{{lng}}/{{ns}}.json'可以正常工作,但是我的情况是我在其他服务器上设置了资源文件,例如“ http://yyyy.com/locales/ {{ lng}} / {{ns}}。json“文件已通过网络分流器加载,但没有数据。

如果我使用loadPath:'http://192.168.1.100/locales/{{lng}}/{{ns}}.json' enter image description here

如果我使用loadPath:'/locales/{{lng}}/{{ns}}.json' ,在网络中,点击url:http:// localhost:3001 / locales / en / translation.json enter image description here 这两个位于不同位置的文件具有相同的内容。

 import i18n from 'i18next';
 import { initReactI18next } from 'react-i18next';
 import Backend from 'i18next-http-backend';

 export const backendOptions = {
    //loadPath: '/locales/{{lng}}/{{ns}}.json',
    loadPath: 'http://192.168.1.100/locales/{{lng}}/{{ns}}.json',

    crossDomain: true,
    requestOptions: {
       mode: 'no-cors',
       credentials: 'include',
       cache: 'default'
   },
   customHeaders: {
    "Access-Control-Allow-Origin": "*",
    "Content-Type": "application/json",
    "Accept": "*/*"
   },
}

i18n
.use(Backend)
//.use(LanguageDetector)
.use(initReactI18next)
.init({
    lng: 'en',
    initImmediate: false,
    fallbackLng: 'en',
    debug: true,
    react: {
        wait: true,
        useSuspense: false
    },
    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
        escapeValue: false, // not needed for react as it escapes by default
    },
    backend: backendOptions
});
export default i18n;

我的问题是我需要从完全不同的目录节点的端点加载资源。

1 个答案:

答案 0 :(得分:0)

您不能在未经允许的情况下向其他域发出Ajax请求,因为这是安全问题。 浏览器阻止您的跨域请求。

您需要在其他域的响应标题中添加CORS标题。