Vue routing stops working when there is no hash in the URL (no designated input file)

I am facing the need to operate Vue router in its default mode, known as hash mode, and unable to use it in history mode. In this mode, all my dynamic routes have a leading hash, like http://myurl.com/#/highlights. However, removing that initial hash, such as http://myurl.com/highlights, causes the website to malfunction with the error message no input file specified.

My objective is to ensure that if none of the routing conditions match and the user is not authenticated, they are redirected to the login screen. Additionally, if the user is authenticated but no routes match, they should be sent to the home page.

Below is the content of my router.js:


import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Programs from './views/Programs.vue'
import Sizzle from './views/Sizzle.vue'
import Login from './views/Login.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: {
        name: "login"
      }
    },
    {
      path: "/login",
      name: "login",
      component: Login,
    },
    {
      path: '/highlights/:slug?',
      name: 'home',
      component: Home,
      props: (route) => ({ slug: route.params.slug || categories[0].slug })
    },
    {
      path: '*',
      redirect: {
        name: "login"
      }
    }
  ]
})

*Please note that the variable categories is created globally as a JavaScript variable before any Vue.js files are loaded using a script tag.

Answer №1

According to official documentation, vue-router typically operates in hash mode, utilizing the URL hash to mimic a complete URL structure without triggering a full page reload when the URL changes.

If you opt for history mode instead, users may encounter a 404 error if they attempt to directly access http://myurl.com/highlights without the appropriate server setup.

To address this issue, simply integrate a catch-all fallback route on your server. This ensures that if the URL doesn't correspond to any static assets, it will serve the same index.html page housing your application.

For additional insights on server configuration, refer to this resource - example-server-configurations

Answer №2

If you want to remove the hash from your URLs, you can utilize the history mode of the router. This feature makes use of the history.pushState API to enable URL navigation without having to reload the entire page:

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

This will help prevent any errors that may occur when using history mode. Just make sure you have the correct server configuration set up,

Here are some Example Server Configurations you can use:

Apache

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

nignx

location / {
  try_files $uri $uri/ /index.html;
}

For more detailed information, please visit the documentation at this link: https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to include my library dependencies in the devDependencies section if I am only planning to publish the library bundle?

When creating a bundle for a library, should the library dependencies be placed in devDependencies? I am developing an NPM library in TypeScript that relies on several dependencies, including React components. As part of the build process, we compile to J ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

Can you tell me the maximum length allowed for the 'key' attribute in Vue.js when rendering a list item?

Is there a maximum size limit for the :key attribute when rendering lists with Vue.js (v2)? If so, what is this limit exactly? In my use case, I am thinking of using :key=JSON.stringify(item) because I am creating a component that needs to handle lists wi ...

Explore nested arrays and retrieve objects that have corresponding categories

Working with react+ nextJS and fetching static objects, specifically "posts". The aim is to develop a "related posts" feature for each post that retrieves three posts containing at least one of the categories. Below is an excerpt simplified for clarity: co ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

update embed - new command

My code below creates a slash command and I'm attempting to update the embed every 10 seconds. const embed = new EmbedBuilder() .setAuthor({ name: track.title, iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) }) .setThumbna ...

What is the best way to transfer data from my browser to the backend of my application?

I am currently working on developing a basic weather application using Express and Node.js. To accomplish this, I need to automatically retrieve the latitude and longitude of the user. While I understand how to achieve this through HTML5 Geolocation in t ...

Why isn't Material UI Data Grid onCellEditCommit working? Wondering if anyone has insight

Having trouble retrieving the data after editing using onCellEditCommit, but it's not functioning properly. This callback is triggered when changes to a cell are committed. Signature: function(params: GridCellEditCommitParams, event: MuiEvent, deta ...

What causes the discrepancy in the output of `document.documentElement.childNodes` in JavaScript?

While working on my code exercise today, I came across a special case regarding the "document.documentElement.childNodes" property. Originally, I believed it to represent all child nodes within a tag as before. However, when implementing my code, I noticed ...

What is the best way to manage the package-lock.json file during deployment from git using SSH?

In my deployment process, I utilize a Git repository to check code in. By using web hooks, a deployment script is triggered on the production server. Once connected to Git via SSH and a .pem key on the server, I perform a Git pull, npm install, webpack bui ...

Issue encountered while attempting to write KML objects to Google Earth API: NPObject error

Currently, I am working on a script that aims to extract data from Facebook and display it graphically on a Google Map using simple extruded polygons. The social integration and AJAX functionality are both working fine for me. However, whenever I try to ex ...

Validating Users with OpenID in Vue.js

Utilizing the oidc-client in a basic VueJs project. The IDP server information is correctly configured in SecurityServices.js, with the following oidc config: var mgr = new Oidc.UserManager({ userStore: new Oidc.WebStorageStateStore(undefined), aut ...

JavaScript and the Firefox Scratchpad platform

Currently, I am utilizing the MDN guide for learning JavaScript and experimenting with examples using scratchpad. Here's a scenario: console.log('The value of b is ' + b); var b; Why does the console log display "The value of b is -1"? I ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Combining Framer Motion with Next.js: Resolving conflicts between layoutId and initial props in page transitions

As I work on creating smooth image page transitions using Framer Motion and Next.js with layoutId, I've come across a challenge. Here is my main objective: The home page displays an overview with 3 images When an image is clicked, the other images f ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

Looking for a solution to troubleshoot issues with the updateServing function in JavaScript?

I am attempting to create a function that will calculate the portion sizes for the ingredients on my website. This function is located in the Recipe.js file and appears as follows: updateServings(type) { // Servings const newServings ...

Error Encountered during Deployment of Custom React App on Heroku due to Fetch API Issue

After developing a small app using React without CRA, I successfully deployed it to Heroku. However, I encountered an issue where a static JSON file that I created isn't fetching properly (it works fine on my local machine). Upon encountering this pr ...

Function execution in React component is not happening

Trying to master React and next.js with Firebase as the database has been an interesting journey. I recently encountered an issue where a function in my component is not being called. Upon trying to debug using console.logs(), it appears that the function ...

Can the color scheme be customized for both light and dark themes in Ant Design version 5?

After creating a hook that successfully toggles between light and dark modes in Chrome's Rendering panel, I noticed that the values in the ConfigProvider remain unchanged when switching themes. Can anyone suggest a workaround to modify the design toke ...