Home > Software engineering >  Vue router 4 - 404 error page when page is refreshed
Vue router 4 - 404 error page when page is refreshed

Time:01-28

I'm working on a wordpress headless theme using vue 3. I've implemented vue router and it seems working correctly when the page is loaded, but I've noticed that when the user change the route and refresh the page, a 404 error page will be displayed to the user.

This is the code I have in my router file

import { createRouter, createWebHistory } from 'vue-router'
//
import UserLanding from '../components/UserLanding.vue'
import UserRegistration from '../components/UserRegistration.vue'

const router = createRouter({
    history: createWebHistory(window.location.pathname),
    routes: [
        {
            name: 'UserLanding',
            path: '/',
            component: UserLanding
        },
        {
            name: 'UserRegistration',
            path: '/registration',
            component: UserRegistration 
        }
    ]
})

export default router
# BEGIN WordPress
# Le direttive (linee) tra `BEGIN WordPress` e `END WordPress` sono
# generate dinamicamente, e dovrebbero essere modificate solo tramite i filtri di WordPress.
# Ogni modifica alle direttive tra questi marcatori verrà sovrascritta.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /wpdev/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wpdev/index.php [L]
</IfModule>

# END WordPress

<IfModule mod_rewrite.c>
Options All -Indexes
</IfModule>

Is there any way to make the things working as expected? Do I need to do a particular configuration on .htaccess or in WP functions file of the theme to avoid that when the page is reloaded the error occur?

Why vue router will not reload the desired route?

CodePudding user response:

You will need to configure your server to handle the routes correctly using the .htaccess file to redirect all requests to the index.php file, which will then handle the routing on the client-side using Vue Router.

You can add the following in your .htaccess file, after the WordPress routing rules:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /wpdev/
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

CodePudding user response:

Wou need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!

Check the Example Server Configurations to do it for your server.

  • Related