[Vuejs]-How do I handle url data between domain and hashtag with Vue Router?

0👍

The hash-routing mechanism is mainly for client-side routing, and should have nothing to do with the server (ruling out 301 Redirects).

When you’re requesting “localhost:8080/foo”, the server is listening for the “/foo” URI, while anything after a hash e.g. “/foo#main”, “main” here will be ignored. The #main is only used client-side for presenting different browser output.

I’ve not tested it, but maye you could use some kind of Navigation Guard, and do some checks, or otherwise perhaps check for some user state on page visit with something like this:

if (user === null) {
    window.location.href = '' // Default link
} else {
  return;
}

0👍

Since you only have this problem if the user navigates to the url themselves, you can use a created lifecycle hook in your main component and look at window.location. If window.location.pathname is not empty or a single slash, you know they navigated to a custom url. You can then redirect the user client side to the right url. The nice part is that you do not need to worry about which urls to redirect on the server side, especially if you run more than the Vue frontend on the server, since the redirect only takes place when your Vue application is loaded.

// App.vue
created () {
  const pathname = window.location.pathname;
  if (['', '/'].indexOf(pathname) === -1) {
    window.location = `/#${pathname}`
  }
}

Edit Vue Template

0👍

I ended up finding a solution by adding this to my server.js file:

if (req.url !== '/' && !req.url.includes('static'))
    res.redirect(`/#${req.url}`);  

I imagine there are some cases that this won’t work for but so far it’s looking good. If a user tries to access domain.com/foo, this will redirect them to domain.com/#/foo and the correct page will be shown. If the user entered domain.com/#/anything/at/all all the server.js sees is ‘/’ and vue router takes care of it. Thanks for the help all!

Leave a comment