Error 401 Unauthorized Token authentication with Node, Vue, axios, and jwt

I am in the middle of a course where tentatively we are using a fixed token validator in the application like this:

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 normally to the bank and it validates whether or not the user is administrator, but by the application it seems that it does not recognize or as logged in the way it is... Any tips what could be happening?

Repository Link: https://github.com/omnweb/Knowledge-Base-Project

Author: Neto Matiazi, 2020-10-27

1 answers

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

Take a look at this code from another project I'm working on that I used knowledge base.

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()
    }
}
 0
Author: Rafaela Ribeiro, 2020-10-27 17:43:18