Multi-language routes in express.js?

后端 未结 5 1553
终归单人心
终归单人心 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条回答
  •  猫巷女王i
    2020-12-29 07:59

    i have done the following: install i18n-node modul and register in the express js. here is code.

    var express = require('express')
      , routes = require('./routes')
      , http = require('http')
      , i18n = require("i18n");
    
      var app = express();
    
    i18n.configure({
        // setup some locales - other locales default to en silently
        locales:['de', 'en'],
        // disable locale file updates
        updateFiles: false
    });
    
    app.configure(function(){
      ...
      app.use(i18n.init);
      ...
    });
    // register helpers for use in templates
    app.locals({
      __i: i18n.__,
      __n: i18n.__n
    });
    

    after this set the following to get all request

    // invoked before each action
    app.all('*', function(req, res, next) {
        // set locale
        var rxLocal = /^\/(de|en)/i;
        if(rxLocal.test(req.url)){
            var arr = rxLocal.exec(req.url);
            var local=arr[1];
            i18n.setLocale(local);
        } else {
            i18n.setLocale('de');
        }
        // add extra logic
        next();
    });
    
    app.get(/\/(de|en)\/login/i, routes.login);
    

    maybe this help.

提交回复
热议问题