VueJS router configuration not enabled

306 Views Asked by At

In my VueJS project, I have configured the routing in a file "router.js".

import VueRouter from 'vue-router'
import personDetails from './components/component.vue'

Vue.use(VueRouter)

export default new VueRouter({
    mode : 'history',
    base : '/',
    routes : [
        {
            path : '/:group/:id',
            name : 'personDetails',
            component : personDetails ,
            props : true
        }
    ]
})

In the main.js file, I enable the routing configuration like this:

import App from './App.vue'
import router from './router'
new Vue({
  router,
  el : '#app',
 components : { App }
 }).$mount('#app')

This is my App.js file:

<template>
  <div id="app">
    <router-view v-bind="$props" />
  </div>
</template>
<script>

export default {
  name: 'App',
  props : ['group', 'id'],
  mounted() {
    console.log('Mounted App')    
  }
}    
</script>

I run the project by running "vue-cli-service build" and "npx http-server ./dist" commands.

I notice that when I call the configured router like this - "http://localhost:8080/1234/56", I get a 404 error. However when I call the default URL "http://localhost:8080" I get a blank page, since the App is loaded without any routing parameters. I can see the console.log() statements added to main.js and App.js, but not the "personDetails" component.

I added a default router configuration, and that seems to be working.

{
   path : '/',
   redirect:'/456/123'
}

This default routing loads the 'personDetails' component with the path parameters mapped to 456 and 123.

Please give some tips to debug this?

2

There are 2 best solutions below

0
On BEST ANSWER

This is due to mode: 'history'. More details here - HTML5 History Mode

Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser.

To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in.

1
On

You can use the fallback proxy of http-server as a catch-all redirect: npx http-server ./dist -P http://localhost:8080?