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.
http://example.com/stats does not work, I'm redirected to / and it loads the App component<router-link :to="/stats">Go to stats</router-link> works perfectlyI 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?
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()!
}
});
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With