Issue with vue-router redirection when pushing a route

I have set up my router configuration as follows:

const router = new Router({
  mode: 'history',

  routes: [
    // root
    {
      path: '/',
      component: ComponentPage,
      redirect: routePrefix.public,
      children: [

        // public
        {
          path: routePrefix.public,
          component: ComponentPage,
          redirect: `${routePrefix.public}/login`,
          children: [
            {
              path: `${routePrefix.public}/login`, component: LoginPage,
            }],
        },

        // private
        {
          path: routePrefix.private,
          component: ComponentPage,
          children: [
            {
              path: `${routePrefix.private}/u`, component: PrivatePage,
            }],
        }],
    }],
});

In my setup, there are two main parts - a public section and a private section. In addition to this, I have configured a navigation guard for authorization:

router.beforeEach((to, from, next) => {
  console.log(`registered request to redirect from 
    '${from.fullPath}' to '${to.fullPath}'`);

  if (to.fullPath.startsWith(routePrefix.private) &&
    !Store.getters['auth/isAuthenticated']) {
    console.log('-> reroute to public main');
    next(routePrefix.public);
  } else if (to.fullPath.startsWith(routePrefix.public) &&
    Store.getters['auth/isAuthenticated']) {
    console.log('-> reroute to private main');
    next(routePrefix.private);
  } else {
    next();
  }
});

If you're curious about the route prefixes used, here they are:

const routePrefix = {
  public: '/p', private: '/x',
};

Nothing incredibly unique.

The Issue

When I access the page localhost:8080/, it correctly redirects from / to /p/login. After successfully logging in, I execute Router.push('/') with the intention of triggering another redirection for the user.

The expected behavior is for / to redirect back to /p/login; then, the navigation guard should step in and direct it to /x/... However, this does not happen. The page remains on /.

Shouldn't it automatically redirect away from the home page? How can I address this issue?

Answer №1

Instead of relying on the rerouting feature, I successfully reached my destination by taking matters into my own hands and pushing through directly. It was a simple yet effective solution that got the job done.

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

Angular filter within a nested ng-repeat loop

I've encountered an issue with nested filtering in Angular, where two filters are dependent on each other. What I'm trying to achieve is the following: <div ng-repeat="g in groups | filter:groupFilter"> ... <tr ng-repeat="c in g.co ...

Struggling to verify HTTP GET Request in Node.js with Express.js authentication

Attempting to send data via a Get Request, the recipient is utilizing basicauth-middleware for authentication purposes. Authentication through the browser and within the original program (without sending data) is successful, with a confirmation message ind ...

Node.js Express JS is currently in the process of retrieving a file

I'm currently grappling with an issue while attempting to download a file using express js. Here is the function in question: var download = function(uri, filename, callback) { request .get(uri) .on('response', function (response) { ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

What steps do I need to take to create a custom image for a website?

I'm looking for a way to create a website image using just code, without the need for an actual image file or image tag. Is there a method to do this? Would I use CSS, Javascript, or HTML5 for this task? If using JavaScript to dynamically generate the ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

What is the best way to show JavaScript output with span style?

I have added a translation feature that allows users to switch paragraphs to French when clicked. Each paragraph now has the first word wrapped in a span with a CSS class that enlarges and colors the text. However, I am facing an issue where when switchi ...

Is there a way to pre-format a phone number field using jQuery?

Looking to create a phone number text field with a pre-formatted 10-digit structure, like this: |( ) - | allowing users to input numbers and have them fill in automatically: |(804) 479-1832| I came across a helpful script for formatting input d ...

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

The Vue SCSS scope feature doesn't seem to apply to the main/root element

One of my components includes a b-modal on its root element. <template> <b-modal ref="mymodal" modal-class="my-modal"> In the SCSS file, I have set some margin styles. <style lang="scss"> .my-modal { margin-top: 100px; This se ...

Submitting a form via axios using AxiosInstance for the POST request

I'm trying to figure out how to send a binary file using axios post request- let data= await axios.post(url, formDataObj,config) The formDataObj is an object of FormData and the config is an object that contains headers for the API So far, everythin ...

Error: Vue cannot be created due to lack of permissions

Can anyone assist me with this issue I'm having while trying to install a Vue app using the command "npm init vue@latest"? Unfortunately, I keep encountering an error and I've tried various solutions such as executing "chmod -R 755 .npm" and "sud ...

jQuery's Multi-Category Filter feature allows users to filter content

I have been working on creating a filter function for my product list. The idea is that when one or more attributes are selected, it should fade out the elements that do not match. And then, if a filter is removed, those faded-out items should fade back in ...

Mapping through an undefined array in React causing an error: "map of undefined"

To display an image, title, and description in the browser, the data is stored in an array in a file named customData.js. Below is an example of the data structure: var DATA = [ { name: 'John Smith', imgURL: 'http://whi ...

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

Handling AJAX requests using jQuery

I'm currently in the process of learning how to utilize jQuery Ajax. Could you explain to me the significance of function(response), as well as what exactly is meant by response == 1 and response == 2? jQuery.post(ajaxurl, data, function(response) { ...

Managing complex chains of asynchronous functions to produce a consolidated result

Running on my backend server with express, I have the following: app.post("/login", async(req, res) => { try { const { username, password } = req.body; let result = await checkCredentials(username, password) console.log("resu ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Reflecting the Old Array in Vue with the New Array

I am currently working with two arrays that I have declared in my data section. data() { return { infeed_data:[], infeed_model:[], } }, After the page is mounted, a specific method is triggered to retrieve roll ...

Vuex state changes causing promises to return undefined

I am having trouble getting the error response from a promise reject to my method. The response is empty inside the method's then() function. How can I retrieve the error response for further use, or handle it inside the catch function? Below is my v ...