Multi-language routes in express.js?

后端 未结 5 1528
终归单人心
终归单人心 2020-12-29 07:30

I\'m wondering if there is a best practise example on how to implement multi-lanuage routes in express.js. i want to use the accept-language header to get the b

5条回答
  •  一生所求
    2020-12-29 07:46

    Middleware recommendation

    The answer by @miro is very good but can be improved as in the following middleware in a separate file (as @ebohlman suggests).

    The middleware

    module.exports = {
      configure: function(app, i18n, config) {
        app.locals.i18n = config;
        i18n.configure(config);
      },
      init: function(req, res, next) {
        var rxLocale = /^\/(\w\w)/i;
        if (rxLocale.test(req.url)){
          var locale = rxLocale.exec(req.url)[1];
          if (req.app.locals.i18n.locales.indexOf(locale) >= 0)
            req.setLocale(locale);
        }
        //else // no need to set the already default
        next();
      },
      url: function(app, url) {
        var locales = app.locals.i18n.locales;
        var urls = [];
        for (var i = 0; i < locales.length; i++)
          urls[i] = '/' + locales[i] + url;
        urls[i] = url;
        return urls;
      }
    };
    

    Also in sample project in github.

    Explanation

    The middleware has three functions. The first is a small helper that configures i18n-node and also saves the settings in app.locals (haven't figured out how to access the settings from i18n-node itself).

    The main one is the second, which takes the locale from the url and sets it in the request object.

    The last one is a helper which, for a given url, returns an array with all possible locales. Eg calling it with '/about' we would get ['/en/about', ..., '/about'].

    How to use

    In app.js:

    // include
    var i18n = require('i18n');
    var services = require('./services');
    
    // configure
    services.i18nUrls.configure(app, i18n, {
      locales: ['el', 'en'],
      defaultLocale: 'el'
    });
    
    // add middleware after static
    app.use(services.i18nUrls.init);
    
    // router
    app.use(services.i18nUrls.url(app, '/'), routes);
    

    Github link

    The locale can be accessed from eg any controller with i18n-node's req.getLocale().

    RFC

    What @josh3736 recommends is surely compliant with RFC etc. Nevertheless, this is a quite common requirement for many i18n web sites and apps, and even Google respects same resources localised and served under different urls (can verify this in webmaster tools). What I would recommended though is to have the same alias after the lang code, eg /en/home, /de/home etc.

提交回复
热议问题