0

I am using mashpie i18n localization package in my nodeJS application. Here is the github link of the same package.

Here is my app.js code:-

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()); // displays en as locale
    next();
});

This is the header data I am sending:-

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

This code is acting strangely. If I try to display accept-language value via console.log, I see 'ar' is getting displayed. However, this particular line

console.log('Get after set locale', i18n.getLocale());

displays 'en' as locale. That means somehow 'ar' is not getting set as locale, but 'en' is getting set. However if I make the following changes-

i18n.configure({
    locales         : ['en','arabic'],
    ...............
    ...............
});

and then send accept-language value as 'arabic' instead of 'ar', the line of code

console.log('Get after set locale', i18n.getLocale());

displays 'arabic' as locale.

Seems like 'ar' has some issue with i18n. How to fix this?

Saswat
  • 12,320
  • 16
  • 77
  • 156
  • I just tried it out and I see no issues this is [my code](https://i.stack.imgur.com/su5ES.png) and it's working as expected – balexandre Jul 26 '23 at 19:29
  • also tried with [ExpressJs](https://i.stack.imgur.com/n1XP8.png) and I think it's the way you are using `getLocale` it should be `req.getLocale()` and not the global instance as that uses the locale initiated when called `init`, in your case will always be `en`, but you can override that with `setLocale()` as the [docs mention](https://github.com/mashpie/i18n-node#i18nsetlocale) -> _"Use setLocale to change any initial locale that was set in i18n.init()."_ – balexandre Jul 26 '23 at 19:41

0 Answers0