【问题标题】:How to handle large number of redirects in Node/Vue app?如何处理 Node/Vue 应用程序中的大量重定向?
【发布时间】:2018-10-03 22:26:35
【问题描述】:

我正在将现有应用程序迁移到在后端使用 Node 和 MongoDB 并在前端使用 Vue 的新技术堆栈。我有相当多的页面需要重定向到新的 URL(超过 50 个)。我知道我可以在前端做这样的事情:

const appRouter = new Router({
  mode: 'history',
  routes: [
    { path: '/a', redirect: '/a2' },
    { path: '/b', redirect: '/b2' },
    { path: '/c', redirect: '/c2' },
  ]
});

但它并没有让我觉得特别优雅。我可以看到将重定向保存在另一个文件中并导入它们以使我的路由器文件更整洁,但这似乎只是格式化的好处。

我想知道其他人如何在 Vue 中处理大量重定向?在服务器级别使用 Node 会更好吗?

【问题讨论】:

  • 使用正则表达式匹配将是一种选择。

标签: node.js vue.js url-redirection vue-router


【解决方案1】:

我有相当多的页面需要重定向到新的 URL

当我们在像 Vue 和 Vue Router 这样的单页应用程序 (SPA) 的上下文中讨论重定向统一资源定位器 (URL) 时,由像 Node.js 这样的 Web 服务器托管,我们可能意味着以下两种情况之一:

  1. 我们在 Vue SPA 中更改了视图的路径
  2. 我们已将 SPA(资源)的位置从一个位置更改为另一个位置。

要确定您需要执行哪种重定向,我们可以检查 URL 将如何变化。 URL 由以下部分组成:

scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]

默认情况下,Vue Router uses the #fragment (hash) portion of the URL 更改视图,因此如果更改,我们应该使用 Alias or Redirect 重定向。

如果 URL 的任何其他部分发生变化,我们应该让 Node.js 返回一个用于重定向的 HTTP 状态代码,例如 301 Moved Permanently302 Moved Temporarily

【讨论】:

  • 好点!这是正在改变的路径,所以我将在节点服务器上进行 301 重定向。
【解决方案2】:

通常@acdcjunior 的解决方案已经足够好,但有时您可能更喜欢挂钩beforeRouteUpdate 来实现重定向。

您可以查看vue-router: dynamic Routing了解更多详情。

以下是官方文档中的一个简单示例:

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    if ( to.match(new RegExp('your_regex_expression'))) {
        next('redirect_url')
    } else {
        // default
        next()
    }
  }
}

或者在 main.js 中使用global guards:

import router from './router'

router.beforeEach((to, from, next) => {
    if ( to.match(new RegExp('your_regex_expression'))) {
        next('redirect_url')
    } else {
        // default
        next()
    }
})

【讨论】:

    【解决方案3】:

    如果样板是问题,你可以使用类似的东西:

    const router = new VueRouter({
      routes: [
        { path: '/([abc])', redirect: to => {
            returect to.path + '2'; // to.path will be like '/a'
        }}
      ]
    })
    

    注意()里面的部分是一个可以自定义的正则表达式。

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 2021-11-15
      • 2012-01-18
      • 2010-12-31
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2017-06-13
      相关资源
      最近更新 更多