Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Router: URL does not load correct component while router-link does

My project uses Vue2 and Vue Router. I want to be able to load the component Stats by typing in the URL http://example.com/stats.

  1. URL http://example.com/stats does not work, I'm redirected to / and it loads the App component
  2. <router-link :to="/stats">Go to stats</router-link> works perfectly

I would like to know whether it is a Vue Router issue or a server configuration issue. I'd like to mention the fact that I experience this issue both in my localhost and my server using nGinx.

How could I fix this?

app.js:

const routes = [
  { path: '/', component: App },
  { path: '/stats', component: Stats },
  { path: "*", component: PageNotFound },
  { path: '/admin', meta: { requiresAdmin: true }, component: Admin},
  { path: "/not-authorized", component: NotAuthorized },
];

Vue.use(VueRouter);
    
const router = new VueRouter({
  mode: 'history',
  routes,
})

const app = new Vue({
  el: '#app',
  router,
  data () {
    return {}
  },
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAdmin)) {
        if (!Store.state.isAdmin) {
            axios.post('/isAdmin').then((response) => {
                if(response.data.isAdmin){
                    next();
                }
                else {
                    next({
                        path: '/not-authorized',
                    })
                }
            });
        }
        else {
            next();
        }
    }
        else {
            next();
        }
    }
    else {
        next(); // make sure to always call next()!
    }
});
like image 435
Léo Coco Avatar asked Jan 31 '26 07:01

Léo Coco


1 Answers

Have you configured your web-server to return the same page regardless of the URL? That way your app can load, and the URL is preserved so routing can take over and select the right component once it's loaded.

This answer https://stackoverflow.com/a/7027686/7816087 suggests the following config for nginx:

location / {
    try_files $uri /base.html;
}
like image 143
Robert Nagy Avatar answered Feb 01 '26 21:02

Robert Nagy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!