This issue typically occurs because when you refresh the page, the server tries to handle the route, but it doesn't know how to handle the Vue routes. To fix this, you need to configure your server to always serve the index.html file for any route that doesn't match a static file. This way, the Vue router can take over and handle the routing on the client side.
Here are solutions for some common server setups:
For an Apache Server
Create or update the .htaccess file in your project's root directory with the following content:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
For an Nginx Server
Update your Nginx configuration file to include the following:
location / {
try_files $uri $uri/ /index.html;
}
For a Node.js/Express Server
If you are using Express, you can add a catch-all route to serve the index.html file:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
For Vue CLI
If you are using Vue CLI, you can configure the vue.config.js file to handle the history mode of the Vue Router:
module.exports = {
devServer: {
historyApiFallback: true
}
};
Vue Router Configuration
Ensure that your Vue Router is configured to use history mode:
import Vue from 'vue';
import Router from 'vue-router';
import About from './components/About.vue';
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/about',
name: 'About',
component: About
},
// other routes
]
});
By setting up your server to always serve the index.html file for any unknown routes, you allow the Vue Router to handle the routing on the client side, which should resolve the issue of the page not loading correctly after a refresh.