[Vuejs]-Vue call API key on header

0đź‘Ť

âś…

it can get confusing when you’re starting out, and certain terms, like header could mean different things depending on context.

There are several ways you can achieve axios calls in vue.

  • There’s the “easy” one, where you add stuff right into a component
  • you can integrate it into vuex
  • create a custom helper/wrapper function (to use in a component or vuex)
  • use a the vue axios plugin

On top of that there’s more than one ways to implement axios

  • reuse global instance
  • create new instance for every call

without seeing your code it’s hard to know which way you’re using it, but I’m going to try to give steps for a way that should make it easy enough to replicate

create a api.js in your src folder with:

import axios from 'axios'
let TOKEN = null;

export default {
  setHeader(val){
    TOKEN = val;
  },
  fetchUsers: () => {
    const instance = axios.create({
      baseURL: 'https://api.example.com',
      headers: {
        header: TOKEN
      }
    });
    // or: instance.defaults.headers.common['header'] = TOKEN;

    return instance.get('/users')
      .then((result) => {
        this.users = result.data
      })
  }
}

In a component, or Vuex, you can then…

import api from '../api.js'

// set header
api.setHeader('abc123')

// make api call
api.fetchUsers().then(r=> {console.log(r)});

This (though untested code) should work…
It’s not the cleanest way of using it, but should be easy to implement in existing code.

TL;DR;

The reason axios.defaults.headers.common['header'] = '2356yhtujkiw'; doesn’t work is likely because you’ve already created the instance, and are re-using it. Updating the default would only apply for subsequent instances created. The example above gets around that, by not using any defaults, and just inserting the headers in every new instance, which is created for every new call.

Leave a comment