Qiuzman
Qiuzman

Reputation: 1761

How to inject Bearer Token in Axios boot file

Quasar has a different setup using boot files and my current axios.ts looks liek this:

    import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({
  baseURL: 'https://localhost:44362/',
  headers: { 'Content-type': 'application/json' },
});

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios;
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api;
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
});

export { api };

However, to get it to inject the bearer token for every request I need to get to this:

    import Vue from 'vue'
import axios from 'axios'

const client = axios.create({
    baseURL: 'http://localhost:5000/api/pizzavotes',
    json: true
})

export default {
    async execute(method, resource, data) {
        const accessToken = await Vue.prototype.$auth.getAccessToken()
        return client({
            method,
            url: resource,
            data,
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        }).then(req => {
            return req.data
        })
    },
    getAll() {
        return this.execute('get', '/')
    },
    getById(id) {
        return this.execute('get', `/${id}`)
    },
    create(data) {
        return this.execute('post', '/', data)
    },
    update(id, data) {
        return this.execute('put', `/${id}`, data)
    },
}

Not sure how to adapt this code to work with quasar. It is unclear where to put the execute and the other comma separated items.

Upvotes: 2

Views: 944

Answers (2)

eylay
eylay

Reputation: 2168

This is a better way. This way you just add Authorization to your existing headers

import { defineBoot } from '#q-app/wrappers'
import axios from 'axios'

const api = axios.create({ baseURL: process.env.API_URL })

const accessToken = localStorage.getItem('api_token')

export default defineBoot(({ app }) => {

    api.defaults.headers.common['Authorization'] = 'Bearer ' + accessToken

    app.config.globalProperties.$axios = axios

    app.config.globalProperties.$api = api
})

export { api }

Upvotes: 0

Pratik Patel
Pratik Patel

Reputation: 6978

You can use request interceptors with async. Here is a sample code.

import {boot} from 'quasar/wrappers'
import axios from 'axios'

const api = axios.create({
  baseURL: 'https://localhost:44362/'
})

export default boot(({app}) => {
  api.interceptors.request.use(
    async config => {
      const accessToken = await Vue.prototype.$auth.getAccessToken()
      config.headers = {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      }
      return config;
    },
    error => {
      Promise.reject(error)
    });
  app.config.globalProperties.$axios = axios

  app.config.globalProperties.$api = api

})

export {api}

Upvotes: 2

Related Questions