Sunday 25 October 2020

Use Axios inside service in Nuxt (Vue)

I am trying to use nuxt's configured axios instance in service in Nuxt project like this:

import axios from 'axios';

export default {
  async create (user) {
     axios.post('/api/user', { user })
  }
}

I have defined interceptor in plugins folder which add token to header of each request:

export default ({ $axios, store }) => {
  $axios.onRequest((config) => {
    if (store.token) {
      config.headers.common.Authorization = store.token
    }
  })
}

When I use axios in service as I showed request doesn't contain Authorization header.

If I call axios method in components or vuex like this this.$axios then request contains requried header. But this way doesn't work in service because if I use this.$axios in service I got undefined. What is correct way to use configured axios in services in Nuxt or make it injectable in services?



from Use Axios inside service in Nuxt (Vue)

No comments:

Post a Comment