Axios-module: How can I use axios?

Created on 4 Sep 2017  路  24Comments  路  Source: nuxt-community/axios-module

I could not find an accurate way to introduce and use axios
In my code:
_nuxt.config.js_

modules: [
    '@nuxtjs/proxy',
    '@nuxtjs/axios'
  ],
  proxy: {
    '/api/**': 'http://127.0.0.1:8000'
  },
  axios: {
    requestInterceptor: (config, { store }) => {
      if (store.state.token) {
        config.headers.common['Authorization'] = `JWT ${store.state.token}`
      }
      return config
    }
  },

_login.vue_

import { mapActions } from 'vuex'
methods: {
    ...mapActions([
      'login'
    ]),
    handleLogin () {
        this.login({ user: this.formData, axios: this.$axios })
    }
}

_store/index.js_

actions: {
    async login ({ commit }, { user, axios }) {
      try {
        const response = await axios.post('/account/login/', user)
        const data = response.data
        commit('INIT', data)
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error.response.data)
      }
}

I wondered if I had to call axios in this way
Is there a simple way to call axios in index.js?
I tried:
_store/index.js_

actions: {
    async login ({ commit }, user) {
      try {
        const response = await this.$axios.$post('/account/login/', user)
        const data = response.data
        commit('INIT', data)
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error.response.data)
      }
}

and:
_login.vue_

this.login(this.formData)

But i got _TypeError: Cannot read property '$axios' of undefined_
Is not what I missed some steps?Can let me know? Thanks!

This question is available on Nuxt.js community (#c16)
help wanted question

Most helpful comment

is there any way we can improve the sparse docs for this in https://axios.nuxtjs.org/usage.html?

All 24 comments

Hi. Please upgrade nuxt version to rc8. This problem will be resolved.

@pi0 Hi, Thanks for your reply, But I seem to be already in rc8
_package.json_

"dependencies": {
    "@nuxtjs/axios": "^4.0.0",
    "axios": "^0.16.2",
    "muse-ui": "^2.1.0",
    "nuxt": "^1.0.0-rc8",
    "validator": "^8.1.0",
    "vuex-persistedstate": "^2.0.0"
  },

$axios is directly injected into vue? Or need me to manually insert in the plugins

I found that I tried to console.log (this) in store / index.js, but only get a undefined

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = () => new Vuex.Store({
  state: {
  // something
  },
  mutations: {
  // something
  }
})
export default store

Is it because the way to create vuex causes i can not access this in vue instance?

try this:
rm -rf /node_modules
reinstall

@ahDDD would love to see a full example of how you were integrate axios with nuxt? I'm also struggling on understanding how nuxt integrates their modules... I wish it was more like how flask integrates their packages...

Do I have to pass in axios to my vuex action's payload everytime? Can't it be ($axios) imported somehow?

@BruceHem Not anymore. Just use this.$axios inside store actions. (See docs)

@pi0 where do we find this?

@pi0 Yes thanks, I think this issue can be closed now.

If you came here like me and found this answer, it's helpful to know that the link to #store-actions hash link on the README.md no longer works because the README has been moved to a stand alone page, which you can find here: https://axios.nuxtjs.org/usage.html.

hi @pi0

// store/module/actions.js

I tried to use this.$axios.$post but i got an error of undefined

@gomezmark show some code pls

Hi @chanlito

At first, I'm trying to use the baseURL, I doesn't work
then, I tried to change the plugins/axios.

nuxt.config.js

module.exports = {
  mode: 'universal',

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  router: {
    middleware: 'i18n'
  },
  /*
  ** Customize the progress-bar color
  */
  loading: { 
    color: '#ffffff', 
    height : '3px'
  },


  /*
  ** Global CSS
  */
  css: [  
    { rel: 'stylesheet', src : '~/assets/css/helper.css'},
    { rel: 'stylesheet', src : '~/assets/css/font.css'}
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '~/plugins/axios.js',
    '~/plugins/vue-lodash',
    '~/plugins/vue-moment',
    '~/plugins/i18n',
    { src: '~/plugins/vuelidate'},
    { src: '~/plugins/vue-select', ssr: false },
    '~/plugins/vue-mg-checkbox'

  ],


  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://github.com/nuxt-community/axios-module#usage
    '@nuxtjs/axios',
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt'
  ],
  /*
  ** Axios module configuration
  */
  env: {
    baseUrl: process.env.BASE_URL || 'https://example_restapi'
  },
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    baseURL: 'https://example_restapi',
    credentials : true,
    proxy: false,
    debug: true,
    retry: {
      retries: 3
    },
    requestInterceptor: (config, {store}) => {
      config.headers.common['Authorization'] = '';
      config.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;application/json';
      return config
    }
  },


  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      vendor : [
        'axios',
        'vuelidate'
      ]
    }
  }
}

~plugins/axios

export default function ({ $axios, redirect }) {
    $axios.defaults.baseURL = 'https://example_restapi';

    $axios.onRequest(config => {
      console.log('Making request to ' + config.url)
    })

    $axios.onError(error => {
      const code = parseInt(error.response && error.response.status)
      if (code === 400) {
        redirect('/400')
      }
    })
  }

~store/modules/phone/actions.js

import Vue from 'vue';
import state from './state';
// import axios from 'axios'
// import axios from '~plugins/axios.js'

const querystring = require('query-string');

const sendVerification = ({ app, commit }, phoneData) => {
    console.log($axios);
    return  this.$axios.$post('/verify/phone', querystring.stringify(phoneData))
                    .then(
                        data => {
                            commit('SET_MOBILE', phoneData);
                            return {
                                valid : true,
                                data  : data
                            }
                        },
                        data => {
                            return {
                                valid : false,
                                data  : data
                            }
                        }
                    );
}

On $axios in actions is not available under this, It's in the context object.

Hi Sir @chanlito,

Im confused. :(
could i import $axios inside the actions?

Don't use arrow function

thanks @chanlito

function sendVerification ({ app, commit }, phoneData) {
    console.log(this);
    return  this.$axios.$post('/verify/phone', querystring.stringify(phoneData))
                    .then(
                        data => {
                            commit('SET_MOBILE', phoneData);
                            return {
                                valid : true,
                                data  : data
                            }
                        },
                        data => {
                            return {
                                valid : false,
                                data  : data
                            }
                        }
                    );
};

on $post.
it became OPTIONS?

@gomezmark I think probably it's the behaviour of axios? Not sure.

is there any way we can improve the sparse docs for this in https://axios.nuxtjs.org/usage.html?

Don't use arrow function

this worked for me. But I think this issue should be documented. :)

here's mine and it work

//action
async fetchMembers ({ commit }) {
const { data } = await this.$axios.get('members')
commit('SET_MEMBERS', data)
}

If someone intends to call axios, call it via dispatch store/index.js

聽聽 export const actions = {
聽聽聽聽 // nuxt server Init only works on store/index.js
聽聽聽聽 async nuxtServerInit ({dispatch}) {
聽聽聽聽聽聽聽聽 let response = await dispatch ('member / list', {page: 1});
聽聽聽聽聽聽聽聽 console.log (response);
聽聽聽聽聽聽 }
}

module file member.js

聽聽 async list ({commit}, payload) {
聽聽聽聽聽聽聽聽 return await this. $ axios. $ post ('/ user / list', payload) .then ((response) => {
聽聽聽聽聽聽聽聽聽聽聽聽 commit ('fetchSuccess', response);
聽聽聽聽聽聽聽聽聽聽聽聽 return response;
聽聽聽聽聽聽聽聽聽聽聽聽 })
聽聽聽聽聽聽聽聽聽聽聽聽 .catch (error => {
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 return error.response.data;
聽聽聽聽聽聽聽聽聽聽聽聽 });
聽聽聽聽 },

file nuxt.config.js config with axios api

 axios: {
    baseURL: 'http://localhost:9020/api'
  },

Sorry if the answer is not appropriate but someone will need to hope that this explains them

Hi. Please upgrade nuxt version to rc8. This problem will be resolved.

this is a lie...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jb-alvarado picture jb-alvarado  路  3Comments

chrislentz picture chrislentz  路  3Comments

gammpamm picture gammpamm  路  4Comments

altafsayani picture altafsayani  路  3Comments

cawa-93 picture cawa-93  路  4Comments