fix: 修复前端语言切换时后端 header 未更新的问题

- 统一 localStorage key:LanguageSwitcher 同时保存到 i18n_language 和 i18nextLng
- 优化 API 请求拦截器:添加 getCurrentLanguage() 函数,优先从 localStorage 读取最新语言设置
- 支持兼容性:同时读取 i18n_language 和 i18nextLng(i18next 默认 key)
- 规范化语言格式:确保返回正确的语言代码(zh-CN, zh-TW, en)
This commit is contained in:
WrBug
2025-12-05 02:33:02 +08:00
parent 777710c2ed
commit d0b454e7c8
4 changed files with 34 additions and 267 deletions
+31 -2
View File
@@ -27,6 +27,35 @@ const apiClient: AxiosInstance = axios.create({
}
})
/**
* 获取当前语言设置(优先从 localStorage 读取,确保获取最新值)
*/
const getCurrentLanguage = (): string => {
// 优先从 localStorage 读取用户设置的语言(统一使用 i18n_language
let savedLanguage = localStorage.getItem('i18n_language')
// 如果 i18n_language 不存在,尝试从 i18nextLng 读取(i18next 默认使用的 key
if (!savedLanguage) {
savedLanguage = localStorage.getItem('i18nextLng')
}
// 如果设置了具体语言,使用设置的语言
if (savedLanguage && savedLanguage !== 'auto' && ['zh-CN', 'zh-TW', 'en'].includes(savedLanguage)) {
return savedLanguage
}
// 如果设置为 auto 或未设置,使用 i18n 的当前语言
// 如果 i18n.language 也没有,使用默认值 'en'
const currentLang = i18n.language || 'en'
// 确保返回的语言格式正确(移除可能的区域代码,如 'en-US' -> 'en'
if (currentLang.startsWith('zh-CN')) return 'zh-CN'
if (currentLang.startsWith('zh-TW') || currentLang.startsWith('zh-HK')) return 'zh-TW'
if (currentLang.startsWith('en')) return 'en'
return 'en'
}
/**
* 请求拦截器
*/
@@ -37,8 +66,8 @@ apiClient.interceptors.request.use(
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
// 添加语言 Header
const language = i18n.language || 'en'
// 添加语言 Header(每次请求都获取最新值)
const language = getCurrentLanguage()
config.headers['X-Language'] = language
return config
},