首页 > 解决方案 > 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

标签: javascripthtmlnode.jsexpressmiddleware

解决方案


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

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

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

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

第一个是检查语言环境是否可用的中间件。

在每个路由器中,根据区域设置检查 slug。如果不对应,只需调用next()方法...

//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();
    }
};

在这种情况下,一个想法是将映射导出到另一个文件中以使其可读......


推荐阅读