vue js:routes not found when page reloads


vue js:routes not found when page reloads



Here is simple vue-routing


const Foo = { template: '

foo
' }
const Bar = { template: '
bar
' }


const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
];
const router = new VueRouter({
routes:routes,
mode: 'history'
});

var app = new Vue({
router,
data: {
message: 'Hello Vue!'
},
mounted:function(){

}
}).$mount('#app');



In HTML


<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
<router-view></router-view>



The links loaded properly (ie :/foo and /bar) when i click on it but if i refresh any vue routed url (ie /foo or /bar) url i will get error message


/foo


/bar


/foo


/bar



cannot get the page



I am serving it with simple express server


app.get('/', (req, res) => res.sendFile('index.html',{ root : __dirname}))





is this happenning locally or on prod? Are you using the webpack template? because, there are various solutions for this depending on the issue
– samayo
Jan 25 at 13:45





its happening on local i am not using webpack build everything included in index.html file and it serves with express
– iam batman
Jan 25 at 13:47






you need to install connect-history-api-fallback for the htm5 api fall back as shown and configure your express as shown here stackoverflow.com/questions/48277747/…
– samayo
Jan 25 at 13:54


connect-history-api-fallback





Hou have to point all routes to index.html like: app.get('*'...
– malcolm
Jan 25 at 13:55


index.html


app.get('*'...





@samayo i have installed that connect-history-api-fallback and configured but it doesn't worked for me
– iam batman
Jan 25 at 14:02




2 Answers
2



You have to redirect all the routes to main file index.html.


index.html


app.get('/', (req, res) => res.sendFile('index.html',{ root : __dirname}))
app.get('*', (req, res) => res.sendFile('index.html',{ root : __dirname}))





Its not worked for me
– iam batman
Jan 25 at 13:58



You have to redirect all the routes to main file index.html, but after of your route main, so:


index.html


//route main
app.use('/api/example', require('./routes/example'));
//routes auxiliary
app.get('/', (req, res) => res.sendFile('index.html', { root : __dirname + '/public'}))
app.get('*', (req, res) => res.sendFile('index.html', { root : __dirname + '/public'}))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift