guide to setting up router access using token

I've received a token from the backend

 axios.post(process.env.VUE_APP_LOGIN, payload)
        .then(response => {
          const {access_token, token_type, user} = response.data;
          this.token = access_token
          this.$store.commit('auth/set_Token', access_token)
          this.store.commit('auth/set_User', user)
          this.$store.commit('auth/set_TokenType', token_type)
          axios.defaults.headers.post['Authorization'] = `Bearer ${access_token}`

Now, I want to set up routes for both public and authenticated users. However, I'm unsure of how to verify and apply the header [authenticated]

Vue.use(VueRouter)


const routes = [
    {
        name: 'DataBase',
        path: '/table',
        component: Table,
    },
    {
        name: 'Home',
        path: '/',
        component: Main,
    },
    {
        name: 'Login',
        path: '/login',
        component: Login,
        meta: {
            public: true,
            hideHeader: true,
            hideFooter: true,
        },

    },
    {
      name: 'Dictionary',
      path: '/dovid',
      component: Dovid,
      meta: {
          
      }
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

Do I need to use router.beforeEach()? Or is there another method I should be using? Any recommended documentation would be appreciated.

Answer №1

One solution is to utilize "router.beforeEach" in your Vue.js application. Take a look at the code snippet below for reference:

router.beforeEach((to, from, next) => {
// Check if route requires authentication and user is not logged in
if (to.matched.some(matchAuthProtectedRoute) && !isLogged()) {
    // Redirect user to login page with intended destination
    next({
        path: '/login',
        query: {
            back: to.fullPath
        }
    });

    return;
}

// Continue navigating to requested route
next();
});

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

What is the best way to bundle a node module with the choice of adding submodules?

I am in the process of developing a JavaScript library that consists of a central core module and multiple optional submodules that enhance the functionalities of the core module. This library is specifically designed for the browser environment, utilizing ...

Enhance tick labels in C3.js with supplementary information

I need a specific format for the tick: tick: { fit: true, multiline: false, outer: false, format: function (x) { var value = this.api.ca ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

Crisscrossed JavaScript Object: recursion and "intricate" conversion (using lodash)

Apologies for the complexity of this example; I've condensed it as much as possible to demonstrate what I'm aiming for I have a complicated structure that needs to be traversed and transformed based on certain conditions. Here's a brief exa ...

What causes my slider to speed up with an increase in items and slow down with fewer items in bxslider?

Find more information here jQuery('.homepage_slider').bxSlider( { minSlides: 1, maxSlides: 4, slideWidth: 200, slideMargin: 30, ...

What is the best approach for testing the TypeScript code below?

Testing the following code has been requested, although I am not familiar with it. import AWS from 'aws-sdk'; import db from './db'; async function uploadUserInfo(userID: number) { const user = db.findByPk(userID); if(!user) throw ...

Developing an interactive graph with Django and harnessing the power of chart.js

I’m currently navigating the world of Django as a newcomer. My current project involves conducting sentiment analysis on real-time user tweets using the Twitter API. I've successfully analyzed and displayed the sentiments extracted from these tweets ...

Webpack 5 is unable to load animated gif files

Hello, I am currently diving into webpack and following the official documentation at https://webpack.js.org/guides/asset-management/#setup. My goal is to incorporate an animated gif using webpack 5. Although the placeholder for the gif is loading, I enco ...

Experiencing Limitations with Node.JS node-hbase Scan Functionality, Unable to Retrieve More than 1000

I am facing an issue while trying to retrieve records from an HBase table in Node.JS using the node-hbase module, which connects to the rest server. I am able to fetch the first batch of records successfully, but I am struggling to get the next set of re ...

Validating Angular UI Route state with Protractor

I've been experimenting with the protractor framework to conduct tests on my angular application. Is it possible for me to verify the angular state during an end-to-end test? ...

The functionality of the Hubot script is restricted to Slack conversations where I initiate a direct message with the

At this very moment, my automated Hubot assistant is functioning properly. When I send the following message via direct message to the robot in Slack: qbot !npm bower The response provided by the robot contains a link: https://www.npmjs.com/package/bowe ...

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...

The technique for accessing nested key-value pairs in a JSON object within an Angular application

After receiving the response from the backend, I have retrieved a nested hash map structure where one hash map is nested within another: hmap.put(l,hmaps); //hmap within hmap When returning the response to the frontend, I am using the ResponseEntity meth ...

How does assigning a checkbox's value as 'undefined' result in the addition of ng-invalid?

I'm facing an issue with a checkbox in my Angular project. The checkbox has a false value of undefined, and even though it's not marked as required, the form doesn't validate when I check and uncheck it. This is because the class ng-invalid ...

After making changes to Vue, jQuery's data is now obsolete

Currently, I am in the process of transitioning from Jquery to Vue.js 3. As a result of this migration, Vue updates the DOM while Jquery still contains outdated information. My question is: How can I make Jquery reflect the new data just like Vue and Jav ...

Enhancing AngularJS: Tailored iterations and data manipulations for more advanced grouping beyond basic ng-repeat limitations

Although I found the answer to this issue on Angular.js more complex conditional loops satisfactory and accepted it, I feel there is more to discuss. Let me provide further details that were not included in my initial inquiry. My goal is to transform the ...

Using Javascript to open a new page and execute a script

I need to be able to launch a new window window.open(url,'_blank'); After that, I want to execute a JavaScript script like this: window.open(url,'_blank').ready("javascript code here"); However, I'm unsure how to accomplish thi ...

Upload an array of choices to the server by utilizing ng-model

I have almost resolved my issue, but now I need help with sending the data to the server. In my current situation, there is a form that includes employee details and projects for that employee (which can be multiple). When the user wants to add projects, ...

The action 'addSection' is restricted to private access and can only be utilized internally by the class named 'File'

const versionList = Object.keys(releaseNote) for (const key of versionList) { // Skip a version if none of its release notes are chosen for cherry-picking. const shouldInclude = cherryPick[key].some(Boolean) if (!shouldInclude) { continue } // Include vers ...

An error was encountered when trying to read property '0' of an undefined object in a for loop

Currently, I am working on a project to create a mastermind game. Everything is progressing smoothly, except for one issue that keeps popping up - I keep encountering the error: "uncaught typeerror cannot read property '0' of undefined." fun ...