【问题标题】:Routing for translation url in nodejs expressnodejs express中翻译url的路由
【发布时间】:2019-11-18 20:36:53
【问题描述】:

我想知道如何在nodejs express中为翻译url做路由

我在app.js 有以下路线,我想知道如何以更好的方式做,比如说如果有超过 5 种语言,url 会因语言而异,但会走相同的路线。 如何在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

【问题讨论】:

    标签: javascript html node.js express middleware


    【解决方案1】:
    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();
        }
    };
    

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

    【讨论】:

    • 感谢回复,如果遇到这种情况app.use('/:lang/about', aboutRouter) app.use('/:lang/contact', contactRouter)怎么办
    猜你喜欢
    • 2012-02-22
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2014-10-03
    • 1970-01-01
    • 2021-07-08
    • 2021-10-13
    相关资源
    最近更新 更多