Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expected.

    import { setupLayouts } from 'virtual:generated-layouts'
    import { createRouter, createWebHistory } from 'vue-router'
    import { isUserLoggedIn } from './utils'
    import routes from '~pages'
    import { canNavigate } from '@layouts/plugins/casl'

    const router = createRouter({
      history: createWebHistory(import.meta.env.BASE_URL),
      routes: [
        {
          path: '/',
          redirect: to => {
            const userData = JSON.parse(localStorage.getItem('accessToken') || '{}')

            console.log(userData)
            if (userData)
              return { name: 'pages-misc-coming-soon' }
            else
              return { name: 'login', query: to.query }
          },
        },
        {
          path: '/pages/user-profile',
          redirect: () => ({ name: 'pages-user-profile-tab', params: { tab: 'profile' } }),
        },
        {
          path: '/pages/account-settings',
          redirect: () => ({ name: 'pages-account-settings-tab', params: { tab: 'account' } }),
        },
        ...setupLayouts(routes),
      ],
    })

    router.beforeEach(to => {
      const isLoggedIn = isUserLoggedIn()

      if (canNavigate(to)) {
        if (to.meta.redirectIfLoggedIn && isLoggedIn)
          return '/'
      }
      else {
        if (isLoggedIn)
          return { name: 'not-authorized' }
        else
          return { name: 'login', query: { to: to.name !== 'index' ? to.fullPath : undefined } }
      }
    })

    export default router

Answer №1

When evaluating an empty JSON object ( {} ), it is considered truthy.

To test this, you can run the following code:

if(JSON.parse('{}')) {console.log('11') } else {console.log('22')}

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

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...

Challenges in Implementing Animated Counters on Mobile Platforms

My website is experiencing a strange issue with an animated counter. The counter works fine on desktop browsers, but when viewed on mobile devices in a live setting, it seems to have trouble parsing or converting numbers above 999. This results in the init ...

Bootstrap Collapse function might not function properly immediately following the execution of Collapse Methods

Here is the reference link: http://jsfiddle.net/72nfxgjs/ The code snippet I used is from w3schools: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_collapse&stacked=h <script type="text/javascript"> $("#collapse1").col ...

Swapping out the video in real-time using an on-demand script

Recently, I encountered an issue with my blog's YouTube video switcher. It seems that the videos won't play once they are changed, and it is related to a light YouTube embed script that I found here: . I believe this script was implemented to imp ...

Is it recommended to utilize a "default" key within an object?

Creating a JavaScript application and looking to establish a config object. Here's what I have so far: var config = { localization: { locales: ['en', ..., 'de'], defaultLocale: 'en' } } Consideri ...

Organizing an array of objects within MUI cards based on social media platforms

I'm currently developing an application that showcases athlete data in a grid layout using MUI Grid. The colored borders on the left side of each card are determined by the corresponding social network associated with that athlete. https://i.sstatic. ...

Uploading image files using Node Express and returning them as JSON in an API response

Is it possible to send json along with an image file in Express? I know that you can serve an image using res.sendFile const path = require('path'); app.get('/image/:filename', (req, res, next) => { res.type('png'); r ...

Pass the ID of a dynamic textbox element to a child window upon clicking a link

One of the challenges I'm facing involves a textbox labeled "Branch Code" that links a branch to a corporate card transaction. At times, there is a requirement to split a transaction among multiple branches. To facilitate this process, I am constructi ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Pattern for identifying text that exclusively consists of whitespace characters and `<br>` tags

Here is an example of a string: <br /> <br /> <br /> Sometimes the string can look like this: <br /> <br /> Or simply like this: & ...

Sending information from Vue frontend to Node/Express backend

I need to enable a user to input a city into a text field on the '/' route. Once submitted, I want to redirect to '/result' and display the information. Currently, in order to display the desired information on '/result', I ha ...

Enhancing jQuery Mobile listview with voting buttons on each item row

I am looking to incorporate 2 vote buttons within a jQuery mobile listview, positioned on the left-hand side and centered within each list item. While I have managed to achieve this using javascript, my goal is to accomplish it without any additional scrip ...

Get JSON data through AJAX using two different methods

Help needed: JSON request issue with XMLHttpRequest var xhr = new XMLHttpRequest(); function elenco_studenti() { var url = "/controller?action=student_list"; xhr.responseType = 'text'; xhr.open("GET", url, true); xhr.onreadystat ...

Is it not possible to implement a "literal" component in SFC?

I'm attempting to create a straightforward "literal" component using MyComponent inside a single file component in Vue 3: <template> <MyComponent>aha</MyComponent> </template> <script> import { ref } from "vue"; const ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

Unique version: "Vuejs encountering strange MySQL date formatting"

MySQL stores time in this format: 2022-04-25 11:03:20 However, when displayed on the client with Vue.js, it appears like this: 2022-04-25T09:03:20.000Z Is there a way to display it exactly as it is stored in the database? ...

Ways to activate jQuery validation when submitting a form instead of triggering it on blur

I am currently utilizing the Jquery Validation plugin to validate form fields upon submission. However, I have encountered an issue where incorrect email format triggers a validation message when moving to the next input field. This behavior is undesirable ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

What causes the variation in size between the next/image and img HTML elements?

Two Images, Different Sizes! https://i.sstatic.net/vpoNG.jpg There seems to be a discrepancy in size between the image rendered by the next/img component and the one displayed using the img element. Interestingly, they both use the same image source and ar ...