当我尝试从NodeJS后端获取翻译文件时,请使用React。我的错误越来越少。
访问从源“http://localhost:8080/assets/locales/en/translation.json”获取'http://localhost:3000‘已被CORS策略阻止:请求的资源上没有“访问控制-允许-原产地”标题。如果不透明响应满足您的需要,请将请求的模式设置为“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' }))
})请帮忙谢谢。
发布于 2020-08-21 07:50:00
我解决了这个问题。我只是在静态路径允许代码之后做了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')));https://stackoverflow.com/questions/63504056
复制相似问题