javascript - 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);
第一个是检查语言环境是否可用的中间件。
在每个路由器中,根据区域设置检查 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();
}
};
在这种情况下,一个想法是将映射导出到另一个文件中以使其可读......
推荐阅读
- javascript - 如何向类打字稿添加新功能
- microsoft-graph-api - 使用 OrganizationFromTenantGuidNotFound 调用 Microsoft Graph API 结果
- node.js - Node.js 中的集群和使用 Kubernetes 自动扩展 Web 应用程序是否具有相同的目的?
- android - 在 Android 模拟器中使用 Appium、Cucumber 和 TestNG 并行执行不起作用
- jenkins - Jenkins Windows 服务未启动
- javascript - 一个只允许字母、数字、破折号和点的验证正则表达式看起来如何,强制至少一个点而不是第一个字符?
- c# - 库存检查器代码不起作用,它有一个错误并且无法编译
- android - 在通道 plugins.flutter.io/firebase_core 上找不到方法 Firebase#initializeCore 的实现
- events - 如何禁用右键单击事件或如何隐藏 Autodesk Forge 查看器上的上下文菜单
- delphi - 从 Clever Internet Suite 登录网站