Léo Coco
Léo Coco

Reputation: 4282

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()!
    }
});

Upvotes: 3

Views: 2037

Answers (3)

L&#233;o Coco
L&#233;o Coco

Reputation: 4282

Here is what I did

Route::get('/stats', 'HomeController@home');

Upvotes: 0

Gabriel Robert
Gabriel Robert

Reputation: 3080

Go to your Laravel routes and put this:

Route::any('{all}', function () {
    return view('index'); // if your main view is "index"
})

This will ensure that deep linking is working properly on all request handled by Laravel.

Upvotes: 1

Robert Nagy
Robert Nagy

Reputation: 61

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;
}

Upvotes: 1

Related Questions