axios-module icon indicating copy to clipboard operation
axios-module copied to clipboard

How can I use axios?

Open ahDDD opened this issue 9 years ago • 24 comments

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)

ahDDD avatar Sep 04 '17 10:09 ahDDD

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

pi0 avatar Sep 04 '17 10:09 pi0

@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

ahDDD avatar Sep 05 '17 02:09 ahDDD

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?

ahDDD avatar Sep 05 '17 02:09 ahDDD

try this: rm -rf /node_modules reinstall

falstack avatar Sep 05 '17 12:09 falstack

@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...

rlam3 avatar Oct 09 '17 19:10 rlam3

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

chanlito avatar Oct 25 '17 12:10 chanlito

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

pi0 avatar Oct 25 '17 21:10 pi0

@pi0 where do we find this?

rlam3 avatar Oct 26 '17 16:10 rlam3

https://github.com/nuxt-community/axios-module#store-actions

pi0 avatar Oct 26 '17 19:10 pi0

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

chanlito avatar Oct 27 '17 01:10 chanlito

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.

garrensweet avatar Mar 12 '18 23:03 garrensweet

hi @pi0

// store/module/actions.js

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

gomezmark avatar Apr 26 '18 04:04 gomezmark

@gomezmark show some code pls

chanlito avatar Apr 26 '18 04:04 chanlito

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
                            }
                        }
                    );
}

gomezmark avatar Apr 26 '18 05:04 gomezmark

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

chanlito avatar Apr 26 '18 05:04 chanlito

Hi Sir @chanlito,

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

gomezmark avatar Apr 26 '18 05:04 gomezmark

Don't use arrow function

chanlito avatar Apr 26 '18 05:04 chanlito

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 avatar Apr 26 '18 06:04 gomezmark

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

chanlito avatar Apr 26 '18 07:04 chanlito

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

tetreault avatar Jun 26 '18 15:06 tetreault