Vuetable-2: Global axios settings doesn't get applied

Created on 25 Jul 2017  路  17Comments  路  Source: ratiw/vuetable-2

Hi,

I'm trying to passing the access_token to the API service. I'm using axios interceptor to do it. But it doesn't effect vuetable2

main.js

import axios from 'axios'

// Add a request interceptor
axios.interceptors.request.use(function (config) {
  config.headers = { Authorization: `Bearer ${window.store.get('access_token')}` }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})
import Vuetable from 'vuetable-2/src/components/Vuetable'
import VuetablePaginationInfo from 'vuetable-2/src/components/VuetablePaginationInfo'
import VuetablePagination from 'vuetable-2/src/components/VuetablePagination'

package.json

"vuetable-2": "^1.6.5",
"axios": "^0.16.2",
question

Most helpful comment

Also, please try a new http-fetch prop in the develop branch. See here for a brief description.

All 17 comments

bump

The Solution is to use http-options property like:

<vuetable ref="vuetable" :api-url="/api/users" :http-options="{ headers: {Authorization: 'bearer xxx'} }" :fields="fields"> </vuetable>
for laravel authentication. But I want the global axios configurations to work, but for some reason they don't

@Passionatedreamer In the next release, you should be able to specify the global axios instance to be used inside Vuetable. Unfortunately, I'm fully occupied with another the work and it's very hard to get my hand on the issues.

No my bad, my configurations are being applied, I had some other issue which I resolved. Now my axios configurations are set globally in laravel and they do trickle down to all requests, including vuetable.

@muhammadsaeedparacha Can you share how exactly you made this work? (code sample)
I never managed to get my global axios configuration (interceptors) applied in vuetable. Thanks!

@ratiw I have a related problem!
When I create an axios interceptor in my global app, it can not handle the request axios. However I ran a test including the interceptor within the axios instance of the vutetable-2 plugin and it worked perfectly.

Sending my example in main.js:

import axios from 'axios'

axios.interceptors.request.use(function (config) {
  config.headers.common['Content-Type'] = 'application/json'
  config.headers.common['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLqZ6g'
  config.headers.common['Accept'] = 'Token'
  return config
}, function (error) {
  console.log(error)
  return Promise.reject(error)
})

As mentioned earlier, vuetable-2 does not allow global settings on the axios instance? Can you clarify? Or how do I perform this implementation?

Thanks!

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest',
    'Authorization': 'Bearer',
    'Accept': 'application/json',
};

I have this in my main,js and works fine. I apply the next part of the bearer from user login response.

P.S not sure how to close this issue :\

@muhammadsaeedparacha Yes! for the requests I create, they all work fine.

However the requests within the vuetable-2 component, I can not change the header settings, because the instance is not global.

I hope I'm not talking shit! :(

Use my version of vuetable-2.
I just remove import axios from 'axios' to make it work. But i only test it on Laravel 5.4 / 5.5

npm install https://github.com/ahmadsafar/vuetable-2 --save

@tluciano

Upon reading the description of axios.interceptors, I think it has different behavior than the "interceptors" in vue-resource.

I think you have to use axios.defaults as what @muhammadsaeedparacha has done.

Also, please try a new http-fetch prop in the develop branch. See here for a brief description.

@ratiw Thank you! http-fetch worked well!

Do you have forecast when release 1.7 will be released?

There's still a strange behaviour when using a dist version of vuetable-2. So I set my defaults in Axios and I'm making sure it's being imported into the application way before vuetable-2. To make things simple, I just set the base API URL. Then in my component:

  • if I import VueTable from 'vuetable-2' - then VueTable doesn't use Axios defaults I've set;
  • if I import VueTable from 'vuetable-2/src/components/Vuetable.vue' - the defaults I've set are being used.

@ratiw Could it a bundling issue? I'd really rather avoid setting custom http-fetch or http-options if I've already set those in my Axios defaults.

I did something like:

file: ./axios.js

``
import _axios from 'axios'
import localforage from 'localforage'
import { isEmpty } from 'lodash'

    export const axios = _axios.create({
        baseURL: "API_URL",
        headers:{
            'Content-Type' : 'application/json',
            'Accept': 'Token'
        }
    })


    // set auth token if there is a token in localstorage
    axios.interceptors.request.use(function (config) {

        return localforage.getItem('authtoken').then((authtoken)=> {
            // perhaps here is the place where we can ask API if the token is valid or not
            // sync token, it valid set it or remove it otherwise

            config.headers.common['Authorization'] = 'Bearer ' + authtoken
            return config
        }).catch((err)=>{
            return config
        })

    }, function (error) {
      console.log(error)
      return Promise.reject(error)
    })

    // set token after login success or remove if expired
    export const setHttpToken = (token) => {

        axios.interceptors.request.use(function (config) {
            if(isEmpty(token)){
                config.headers.common['Authorization'] = null
            } else {
                config.headers.common['Authorization'] = "Bearer " + token
            }
            return config
        }, function (error) {
            console.log(error)
            return Promise.reject(error)
        })

    }

``

then used it in vuex actions.js

``
import { axios, setHttpToken } from './axios';
import { isEmpty } from 'lodash';
import localforage from 'localforage';

    export const setToken  = ({ commit, dispatch },token)=> {
        if (isEmpty(token)){
            return dispatch('checkTokenExists').then((token)=>{
                setHttpToken(token)
            }).catch((err)=>{
                return Promise.reject(err)
            })
        }
        commit('SET_TOKEN', token)
        setHttpToken(token)
    }

    export const checkTokenExists  = ({ commit, dispatch },token)=> {
        return localforage.getItem('authtoken').then((authtoken)=>{
            if(isEmpty(authtoken)){
                //dispatch('clearAuth')
                return Promise.reject('NO_STORAGE_TOKEN')
            }

            return Promise.resolve(authtoken)
        })
    }

``

Hi everyone, any update ?

Not sure if this helps, but I kinda do the reverse. My global axios passes the CSRF and Authorization headers as a common header. Sometime I don't want to use them eg. when calling an api from another site.

To achieve it I use a replacement instance to call axios and remove headers. You could use the same to add them.

https://warlord0blog.wordpress.com/2018/08/01/axios-and-the-x-csrf-token/ where $http is axios

for vuetable-2 specifically I replce the default http-fetch with my own. Which pretty much does nothing other than ensure it uses my global axios instance.

      <vuetable
        :http-fetch="getData"
        ...
      />

Then in methods:

    // replaces the vuetales own call to api-url to handle jwt auth
    getData (apiUrl, httpOptions) {
      return this.$http.get(apiUrl, httpOptions)
    },

So in the getData function you could replace it with an instance of axios that add or deletes headers.

This is a design flaw. The axios instance should be assignable to the Vuetable component, so people can use their axios instances properly. Currently it is relying on the global instance, because the Vuetable.vue source code simply routes calls to the import axios from 'axios'; line.

Something like:
```

Was this page helpful?
0 / 5 - 0 ratings

Related issues

anselmobattisti picture anselmobattisti  路  5Comments

PrimozRome picture PrimozRome  路  5Comments

coderabsolute picture coderabsolute  路  4Comments

larryu picture larryu  路  6Comments

jdriesen picture jdriesen  路  4Comments