Passing data from a Vue.js component to a router in index.js

I am attempting to transmit a JWT token value from the component Login.vue and verify it in the router/index.js before directing the user to the next page.

Login.vue:

<script>
import axios from "axios"; 

export default {
  name: "Login",      
  methods: {
    login() {

      let userDetails = {
        'Username' : this.email,
        'Password' : this.password
      }
      axios       
        .post('https://localhost:44349/api/Token/CreateToken',userDetails)
        .then((response) => {      
            this.token  = response.data.token 
            this.$router.push({
                name:'Books', 
                params:{token:this.token}}) // <--- send Token
        })
        .catch((error) => {
            console.log(error)
        });
    }
  }
};
</script>

router/index.js

const router = new Router({    
  routes: [    
    {
      path: '/books',
      name: 'books',
      component: Books,
      props: true,      
       meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    }
  ]
});


router.beforeEach((to, form, next) => {
  if (to.matched.some(rec => rec.meta.requiresAuth)) {   

    let isTokenValid= ??; // How can I retrieve the token?    

    if (isTokenValid) {        
       next();
    } 
    else {          
      next({ name: 'Login' });
    }
  }  
});

export default router 

Answer №1

I opted for utilizing localstorage as a means of storing the token. Another alternative approach is to employ vuex for storage, which you can explore further by checking out this informative guide on Authentication using Vuex

  .then((response) => {  
      this.token  = response.data.token 
       localStorage.setItem('user-token', this.token);
        this.$router.push({
            name:'Books', 
            }) // <--- dispatch Token
    }).catch(){
        localStorage.removeItem('user-token');
    }

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

Navigating Wordpress posts with a Month data format filter in Vue.js

Can anyone suggest the most effective method for filtering WordPress Posts by month using Vue.js? I am currently retrieving my data from WP_JSON posts, but I need a dropdown menu that allows users to select a specific month such as "September" so that onl ...

Exploring the Capabilities of Drag-and-Drop Functionality in jsTree and DataTables

Is it possible to copy nodes from a jsTree that I've dragged to a cell in a DataTable? I'm struggling with getting this functionality to work. Any suggestions on how to achieve this? I am not seeing any alerts appear. This is the HTML code: &l ...

The calculator is malfunctioning and unable to perform calculations

export default function App() { const [activeKey, setActiveKey] = useState(0); const [storeArr, setStoreArr] = useState([]); function click(selector) { setActiveKey(selector); if (activeKey !== "=") { setStoreArr([...storeArr ...

How to access a custom font stored in the assets folder when mounting a Vue component

Is there a way to load a local font upon mounting? The font is stored in the assets folder and I have attempted different methods. I am utilizing the FontFace API to ensure the font loads prior to using it () mounted () { const myFont = new FontFace(&a ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...

What is the reason for receiving the "Must provide query string" error when using the fetch API, but not when using cURL or Postman?

I've been attempting to integrate the graphbrainz library into a React app using the fetch API. No matter how I structure my request body, I keep encountering this error: BadRequestError: Must provide query string. at graphqlMiddleware (C:\U ...

The call stack size has reached its maximum limit due to running 2 Collection.find commands

I've encountered a Maximum call stack size exceeded exception in my Chrome console while working with Angular2 and Meteor. This issue started after I added the following code to my client side: var userChannelsId = UserChannels.find({idUser: Meteor.u ...

The error message "element is not defined" is indicating an issue related to the cordova-plugin-google

In my current project using Ionic 3, I decided to implement map-related features by incorporating the Google Maps plugin recommended by the Ionic Team. This specific plugin serves as a wrapper around cordova-plugin-googlemaps. Following the steps outlined ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

In Internet Explorer 10, it is not possible to access the document.links using the link's id; it can only be accessed using the

Why does the following code work in FireFox 23.0.1 and Chrome 29, but not in IE 10? <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> function loadFile1(){ a ...

Error: The expression `xmlDoc.load` returns a value of undefined, which is not an object

My current challenge involves loading an XML file using Javascript in IE, Firefox, and Safari. I have yet to find a function that works well across all three browsers. The load function I am currently using is similar to the one found in w3schools tutorial ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: Is there a way to hide them from being easily accessible? And most importantly, is it s ...

How can I remove a specific JSON object from localStorage based on the data associated with the element that is currently being clicked on?

Unique Scenario A user interacts with an element, triggering a change in the background image and storing data related to that element in localStorage: this process functions correctly. Next, the toggle variable is set to 0, the background image change ...

Something seems to be amiss with the Vue.js eslint configuration. Can you help

I am just starting out with vueJs. I attempted to use this basic code in my vue project to update the data of a component: <template> <div> <h1> {{ message }} <h2> Hello {{ firstname }} {{ lastna ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Sort activities according to the preferences of the user

This is the concept behind my current design. Click here to view the design When making a GET request, I retrieve data from a MongoDB database and display it on the view. Now, I aim to implement a filter functionality based on user input through a form. ...

What steps are necessary to activate javascript in HTML for WebView?

I recently discovered that when my HTML/JavaScript site is visited via an Android webview, JavaScript is disabled by default. This causes a pricing list on my page to not display properly because it requires a JavaScript class to be added for it to open. I ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...