Home > Net >  404 Error when page gets refreshed/revisited
404 Error when page gets refreshed/revisited

Time:12-15

Tried using history mode in vue.js to remove hash sign from the URL. Downside of this is when the page got refreshed / revisited, it occurs 404 Not Found. There's a documentation from the website about the History Mode and fixing it but I'm having trouble understanding it, sorry.

What I want is remove the history mode from the code, at the same time hash symbol gets removed from the url and 404 Error will be fixed.

I will provide the code below from the index.js that the web has. (Note: The website is already built this way and it was passed onto me since the developer that made this had problems.)

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  mode:"history",
  routes,
});

const isLogin = true;
router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  if (to.name == "login" || isLogin) {
    next();
  } else {
    next("/login");
  }
});
router.beforeResolve((to, from, next) => {
  next();
});
router.afterEach((to, from) => {
});
export default router;

Do I need to do a new set of codes for me to able to do what I want? 404 Error fixed when page got refreshed / revisited, hash symbol gets removed from URL.

CodePudding user response:

The default mode for Vue Router is hash mode. It uses a URL hash to simulate a full URL so that the page won’t be reloaded when the URL changes. Comment or remove mode: "history"

const router = new VueRouter({
  //mode:"history",
  routes,
});

See the example case here https://www.bezkoder.com/integrate-vue-spring-boot/

CodePudding user response:

I encountered this problem some time ago, you just have to configure the vue router mode and install a package for the server, and configure the server as well. I leave the official guide here.

Vue router config:

const router = new VueRouter({
  mode: 'history',//Set the mode to 'history'
  routes: [...]
})

Server config (NOT express):

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.html', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

For express node.js sever: For Node.js/Express, consider using connect-history-api-fallback middleware.

  • Related