Unauthorized Token Authentication with Node, Vue, Xios and jwt

Asked

Viewed 276 times

0

I’m in the middle of a course where on a provisional basis we’re using a fixed token validator in the application in this way:

require('axios').defaults.headers.common['Autorization'] = `bearer ${token}`

This returns an error in the console:

xhr.js?b50d:184 GET http://localhost:3000/users 401 (Unauthorized)
...

The function is as follows:

loadUsers() {
      const url = `${baseApiUrl}/users`;
      axios
        .get(url) 
        .then((res) => {
          this.users = res.data;
    }); 
 },

The base url is imported from an external file.

Using Postman I get access to the bank normally and it validates whether or not the user is administrator, but by the application it seems that not even recognize as logged in the way it is... Any hint of what might be happening?

Link to the repository: https://github.com/omnweb/Knowledge-Base-Project

1 answer

0

I took this course you are doing and it seems that you did not put the token validation in app.See

Take a look at this code from another project I’m working on and I used the basic Knowledge.

import axios from 'axios'
import { baseApiUrl, userKey } from '@/global'
import { mapState } from 'vuex'
import Menu from './components/template/Menu'
import Header from './components/template/Header'
import Content from './components/template/Content'
import Footer from './components/template/Footer'
import Loading from '@/components/template/Loading'

export default {
    name: "App",
    components: { Header, Menu, Content, Footer, Loading },
    computed: mapState(['isMenuVisible', 'user']),
    data: function() {
        return {
            validatingToken: true
        }
    },
    methods: {
        async validateToken() {
            this.validatingToken = true

            const json = localStorage.getItem(userKey)
            const userData = JSON.parse(json)
            this.$store.commit('setUser', null)

            if(!userData) {
                this.validatingToken = false
                this.$router.push({ name: 'auth' })
                return
            }

            const res = await axios.post(`${baseApiUrl}/validateToken`, userData)

            if (res.data) {
                this.$store.commit('setUser', userData)
                
            } else {
                localStorage.removeItem(userKey)
                this.$router.push({ name: 'auth' })
            }

            this.validatingToken = false
        }
    },
    created() {
        this.validateToken()
    }
}

  • Great, thanks for the answer. Is this code from the finished version? I did not conclude yet, I stopped at the part that he said would leave the above code as provisional, only that for me it did not work and from what I could notice he only changes this part of the token code at the end of the course.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.