简体   繁体   中英

Routing for translation url in nodejs express

I would like to know how to do routing for translation url in nodejs express

I have following routes in app.js , I would like to know how to do in a better way, lets say if have more than 5 languages , url will vary according to language but go to same route. How to do in express nodejs.

app.js
app.use(/^\/(en|de)/, langRouter);
app.use(/^\/(en|de)\/((all-services-from|hui-kuan-cong)-(.+)-(to|zhi)-(.+))/, serviceRouter);
app.use('/:lang/route-services-services/:pr', aboutRouter);
app.use('/:lang/ain-jian-wen-ti/:pr', aboutRouter);


frontend urls,
will pass to langRouter
/en 
/de
will pass to serviceRouter
/en/all-services-from-sin-to-mal
/de/hui-kuan-cong-sin-zhi-mal
will pass to aboutRouter
/en/route-services-services/fund
/de/ain-jian-wen-ti/fund

app.use(/:locale*, checkLangRouter);

app.use(/:locale/, langRouter);

app.use(/:locale/:slug/, serviceRouter)

app.use('/:locale/:slug/:pr', aboutRouter);

The first is the middleware to check if the locale is available..

In each router, check the slug depending of the locale. If it's not corresponding, just call the next() method...

//aboutRouter.js

module.exports = (req, res, next) => {
    const locale = req.params.locale;
    const slug = req.params.slug;

    const myMapping = {
         en: 'about',
         fr: 'a-propos',
         it: 'attorno'
    };

    if (myMapping[locale] !== slug) {
         // It's not the about route
         return next();
    }
};

In this case, a conceil will be to export the mapping in another file to make it readable...

In translation in nodeJs Express use i18n ... very simple and easy

https://lokalise.com/blog/node-js-i18n-express-js-localization/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM