Axios not passing headers on requests

12,557

Solution 1

You can use axios.create to create a new axios instance with a config object, including the headers. The configuration will be used for each subsequent calls you make using that instance.

Something like this worked for me:

var App = Vue.component('app', {
  mounted () {
    this.response = null
    this.axiosInstance = axios.create({
      baseURL: 'http://localhost:5000/',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      }
    })
  },
  data () {
    return {
      response: this.response,
    }
  },
  methods: {
    login () {
      this.axiosInstance.post('login', {username: 'test', password: 'test'})
        .then(resp => {
          this.accessToken = resp.data.access_token
          this.axiosInstance.defaults.headers['Authorization'] = 'Bearer ' + this.accessToken
        })
        .catch(err => this.response = err.response.status + ' ' + err.response.statusText)
    },
    protected () {
      this.axiosInstance.get('protected')
        .then(resp => this.response = resp.data)
        .catch(err => this.response = err.response.status + ' ' + err.response.statusText)
    }
  },
  template: '<div><button @click="login">Connect</button><button @click="protected">Protected</button></div>'
})

Solution 2

try this..

//in get request
const auth = {
        headers: {Authorization:'JWT ' + localStorage.getItem('token')} 
    }

axios.get('http://yourapi.com',auth).then(result => { 
 console.log(result.data)
})

//in post request
const auth = {
        headers: {Authorization:'JWT ' + localStorage.getItem('token')} 
    }
 //note:auth will be 3rd parameter in post request
axios.post('http://yourapi.com',{somekey:'some value'},auth).then(result => { 
 console.log(result.data)
})
Share:
12,557
Gustavo Dias
Author by

Gustavo Dias

Updated on June 11, 2022

Comments

  • Gustavo Dias
    Gustavo Dias almost 2 years

    I'm building a VueJS application and I'm using JSON web tokens as my auth system. When I log the user, I store the token with localStorage and works fine. I check the headers and it's in the 'Authorization' param.

    I pass with axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')

    I see the headers and it's okay. But when I execute a get request to an protected route in my API, return 'unauthorized'. But when I pass the header with token manually in the request, works fine.

    Somebody know how to pass the header automatically when executing some request?