Home » vue » Vue is always redirect to home page when I enter an invalid uri

Vue is always redirect to home page when I enter an invalid uri

Posted by: admin November 26, 2021 Leave a comment

Questions:

I`m making a multiple page app with vue-cli 4 and this is part of my configurations in 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'
        }
    },
    ...
}

When I entered a valid uri, such as ‘/’ and ‘/update’, the server works fines. But when I entered a wrong uri, such as ‘/abc’, the server redirects to home page. I hope it returns to 404 page, but I can`t find a solution from the Internet. So how should I do?

By the way, can I use regExp here as a varible? If I can, how can I get the value in pages floder (refers to the picture below). If can`t, how can I achieve it by using another tool?

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

My Program Structure | 20210919003359.png

Finally, this is my dependencies in 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"
}
Answers:

In vue 404 page can easily be setup from the router using a catch all route. Any route that you have not defined will be caught:

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

Documentation from vue router https://router.vuejs.org/guide/essentials/history-mode.html link also goes over setting up 404 page from nginx and regex