【问题标题】:Vue is always redirect to home page when I enter an invalid uri当我输入无效的 uri 时,Vue 总是重定向到主页
【发布时间】:2021-11-13 02:38:24
【问题描述】:

我正在使用 vue-cli 4 制作一个多页面应用程序,这是我在 vue.config.js 中配置的一部分。

module.exports = {
    ...,
    devServer: {
        open: process.platform === 'darwin',
        disableHostCheck: true,
        index: '/index',
        host: 'localhost',
        port: 12000,
        https: false,
        hotOnly: false,
        before: () => {}
    },
    pages: {
        '404': {
            entry: './src/pages/error/404.js',
            template: './src/pages/error/404.html',
            filename: 'error/404.html'
        },
        'index': {
            entry: './src/pages/home/index.js',
            template: './src/pages/home/index.html',
            filename: 'index.html'
        },
        'update': {
            entry: './src/pages/update/index.js',
            template: './src/pages/update/index.html',
            filename: 'update/index.html'
        }
    },
    ...
}

当我输入一个有效的 uri,例如 '/' 和 '/update' 时,服务器可以正常工作。但是当我输入了错误的 uri,例如“/abc”时,服务器会重定向到主页。我希望它返回到 404 页面,但我无法从互联网上找到解决方案。那我该怎么办呢?

顺便问一下,我可以在这里使用 regExp 作为变量吗?如果可以,我怎样才能获得 pages floder 中的值(参考下图)。如果不能,如何使用其他工具来实现?

pages: {
    'update/{variable}': {
        entry: './src/pages/error/404.js',
        template: './src/pages/error/404.html',
        filename: 'error/404.html'
    }
}

My Program Structure | 20210919003359.png

最后,这是我在 package.json 中的依赖:

"dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.2.11",
    "vue-router": "^4.0.11",
    "webpack-bundle-analyzer": "^4.4.2"
},
"devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.2.11",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2"
}

【问题讨论】:

    标签: vue.js vuejs3 vue-cli-4


    【解决方案1】:

    在 vue 404 页面中,可以使用 catch all 路由轻松地从路由器设置。任何你没有定义的路由都会被捕获:

    const router = new VueRouter({
      mode: 'history',
      routes: [
        { 
          path: '/:catchAll(.*)', 
          component: NotFoundComponent,
          name: 'NotFound'
        }
      ]
    }) 
    

    vue 路由器 https://router.vuejs.org/guide/essentials/history-mode.html 链接的文档还介绍了从 nginx 和正则表达式设置 404 页面

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 2023-03-24
      • 2014-07-10
      相关资源
      最近更新 更多