javascript - 快速路由 - 根据区域设置重定向

标签 javascript node.js express routes localization

我正在尝试为我的多语言网站设置路由。我的目标是根据用户的语言(已检测到)重定向​​用户。

这是我当前未完成的代码:

app.get('/(:lang)?', (req, res, next) => {
    const urlLang = req.params.lang || 'en'; // English is default
    const userLang = 'nl'; // Will be detected

    if (urlLang !== userLang) {
        // Wrong URL
        res.redirect(userLang + req.url);
    } else next();
});

在此示例中,我尝试从 url (urlLang) 中减去请求的语言。如果该语言与用户语言不匹配,则应重定向到正确的 URL。

我想要实现的目标的一些示例:

  • 使用语言 en 的用户请求 /:无重定向
  • 使用 nl 语言的用户请求 /:重定向到 /nl
  • 语言为 en 的用户请求 /foo/bar:无重定向
  • 使用 nl 语言的用户请求 /foo/bar:重定向到 /nl/foo/bar

我当前的代码仅在请求的路径为 //:lang 时有效,但不适用于 /home 等路由>/nl/home。我不明白如何通过 express 来实现这一点。任何帮助将不胜感激!

<小时/>

请注意,我已经设置了其他所有内容,例如语言检测、翻译逻辑、 View 等。我只是询问路由。

最佳答案

如果您知道需要提前支持的所有语言标识符,那么这应该可行:

api.get('/(:lang(en|nl)/)?*', ( req, res, next ) => {

关于javascript - 快速路由 - 根据区域设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44500138/

相关文章:

javascript - 获取扩展对象的 TypeScript 代码补全

javascript - 无序列表和动态元素符号图像

node.js - 生成 Node 子进程时不遵守 cwd

node.js - Node/Express : Failed to lookup view "index" in views directory "./app/views"

node.js - heroku 应用程序因 socket.io 崩溃

Javascript 不适用于 Chrome 和 IE,但适用于 Firefox

javascript - Node 找不到模块但它存在于 node_modules 中?

javascript - "errmsg": "E11000 duplicate key error collection: reduxpress.users index: address.email_1 dup key: { : null }"

javascript - Socket IO - 如何让多个管理员用户访问多个 URL 上的多个私有(private)房间

javascript - 单击复选框时无法发出事件。 (socket.io)