【发布时间】: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