从 api 加载翻译时,下面的代码工作正常,但我有一个要求,即“loadPath”中的此请求应使用身份验证令牌发送,否则将收到身份验证错误。我应该在 i18next 代码的“后端”部分将该令牌发送到哪里?
import HttpApi from 'i18next-http-backend';
import XHR from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import i18n from 'i18next';
i18n.use(XHR).use(LanguageDetector)
.use(HttpApi)
.use(initReactI18next)
.init({
supportedLngs: ['en', 'es', 'pt', 'fr', 'gr', 'pl'],
fallbackLng: 'en',
detection: {
order: ['htmlTag','querystring','path','cookie','localStorage','sessionStorage','subdomain'],
caches: ['cookie', 'localStorage'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
lookupSessionStorage: 'i18nextLng'
},
backend: {
loadPath: `${process.env.REACT_APP_BASE + 'locale/guest/en'}`,
parse: function (data:any) {
console.log(JSON.parse(res).data)
return JSON.parse(res).data;
},
},
interpolation: {escapeValue: false},
debug: true,
react: {useSuspense: false}
});
export default i18n;
token
可以在 customHeaders
选项的 backend
部分与 loadPath
一起设置。
例如
backend: {
loadPath: `${process.env.REACT_APP_BASE}locale/guest/en`,
customHeaders: {
authorization: `Bearer ${myToken}`
}
}
如果需要
customHeaders
也可以定义为支持获取最新令牌的函数,例如
backend: {
loadPath: `${process.env.REACT_APP_BASE}locale/guest/en`,
customHeaders: () => {
const myLatestToken = getLatestToken();
return {
authorization: `Bearer ${myLatestToken}`
};
}
}