【问题标题】:i18next backend translation.json fetch problemi18next 后端 translation.json 获取问题
【发布时间】:2020-08-21 15:50:00
【问题描述】:

当我尝试使用 React 从 NodeJS 后端获取翻译文件时。我遇到了错误。

访问获取 来自原点的“http://localhost:8080/assets/locales/en/translation.json” 'http://localhost:3000' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式为“no-cors”以获取禁用 CORS 的资源。

我的反应结构如下;

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

i18n
  // load translation using http -> see /public/locales
  // learn more: https://github.com/i18next/i18next-http-backend
  .use(Backend)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    lng: 'tr',
    fallbackLng: 'tr',
    preload: ['tr', 'en'],
    ns: ['translation'],
    defaultNS: 'translation',
    debug: true,    
    backend: {
      // for all available options read the backend's repository readme file
      loadPath: 'http://localhost:8080/assets/locales/{{lng}}/{{ns}}.json',      
    }
    
  });
export default i18n;

和 NodeJS 是一样的;

app.use('/assets',
    express.static(path.join(__dirname, 'assets')));

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    
    next();
});

如您所见,我授予了对相关文件夹的访问权限,它应该获取 json 文件内容,因为在 NodeJS 方面,如果我尝试使用 i18next 包获取翻译,我可以成功获取它。下面的代码运行没有问题。

const i18next = require('i18next')
const HttpBackend = require('i18next-http-backend')
// const HttpBackend = require('../../cjs')
i18next.use(HttpBackend).init({
  lng: 'en',
  fallbackLng: 'en',
  preload: ['en', 'tr'],
  ns: ['translation'],
  defaultNS: 'translation',
  backend: {
    loadPath: 'http://localhost:8080/assets/locales/{{lng}}/{{ns}}.json'
  }
}, (err, t) => {
  if (err) return console.error(err)
  console.log(t('welcome'))
  console.log(t('welcome', { lng: 'tr' }))
})

请帮忙谢谢。

【问题讨论】:

标签: node.js cors react-i18next


【解决方案1】:

我解决了这个问题。我刚刚在静态路径允许代码之后制作了 CORS 允许代码。所以; 1-请求来自带有标题等的前端,并尝试访问静态本地化文件夹 2- 但是 CORS 策略正在停止请求,因为在到达本地化文件夹时它不活动。

当我像下面这样更改代码的顺序时,它起作用了。

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    
    next();
});

app.use('/assets',
    express.static(path.join(__dirname, 'assets')));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 2017-09-10
    • 2012-10-27
    • 2021-11-04
    • 2021-06-26
    • 2015-12-27
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多