You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中mashpie i18n无法设置'ar'为locale仅支持'arabic'的问题

问题:mashpie i18n无法将'ar'设置为locale的解决方法

我在Node.js应用中使用mashpie i18n国际化包,app.js中的配置代码如下:

i18n.configure({
    locales         : ['en','ar'],
    defaultLocale   : 'en',
    autoReload      : true,
    directory       : __dirname + '/lang',
    synFiles        : true,
    fallbackLng     : "en",
});

// 省略其他代码

app.use(i18n.init);

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    var apiLocale = (req.headers['accept-language']).toLowerCase(); console.log('accept language', apiLocale);
    i18n.setLocale(apiLocale || 'en');
    console.log('Get after set locale', i18n.getLocale()); // 输出en
    next();
});

发送的请求头数据:

Access-Control-Allow-Origin:*
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept
accept-language:ar

运行异常:控制台打印apiLocale为'ar',但调用i18n.setLocale后,getLocale返回'en';若将配置中的locales改为['en','arabic'],同时发送accept-language:arabic请求头,getLocale则正常返回'arabic'。


解决方法

1. 使用请求上下文的locale方法

mashpie i18n在Express中通过i18n.init中间件为每个请求创建独立的locale上下文,全局的i18n.setLocale()无法正确作用于当前请求。需改为调用请求对象的setLocale和getLocale方法:

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    var apiLocale = (req.headers['accept-language'] || 'en').toLowerCase();
    console.log('accept language', apiLocale);
    req.setLocale(apiLocale);
    console.log('Get after set locale', req.getLocale());
    next();
});

2. 验证语言文件命名

确保lang目录下存在ar.json文件,文件名必须与配置locales数组中的'ar'完全一致,文件需包含合法的JSON格式内容(示例):

{
  "hello": "مرحبا"
}

3. 标准化语言码(可选)

若请求头的accept-language包含区域后缀(如'ar-EG'),可先标准化语言码再设置:

var normalizedLocale = i18n.normalizeLocale(apiLocale);
req.setLocale(normalizedLocale);

内容的提问来源于stack exchange,提问作者Saswat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:56:18