axios is not defined in vue js cli

Use following command to install axios

 npm install axios --save

After executing above command import like mentioned below:

import axios from 'axios'

Also install vue-axios and import in main.js

import VueAxios from 'vue-axios'

Then in main.js:

Vue.use(VueAxios, axios)

Now if I am not mistaken in your methods you can use for example:

let uri = 'http://localhost:4000/tickets/add';
this.axios.post(uri, this.ticket).then((response) => {
    console.log(response);
});

Solution 1 (Not recommended):

In main.js, add this line instead of import axios from 'axios'

window.axios = require('axios');

And remove

Vue.use(axios)

Solution 2 (Recommended Approach):

Using window is generally considered a bad practice, so you better use axios the following way:

  1. Create a folder named plugins inside of your src directory.

  2. Then, create axios.js file inside that directory. We will put all our axios logic here and use axios as a Vue plugin.

  3. Add the following:

import ax from 'axios'

// insert all your axios logic here

export const axios = ax

export default {
    install (Vue, options) {
        Vue.prototype.$axios = ax
    }
}
  1. In src/main.js, add the following:
import Vue from 'vue' // You can skip this line
import VueAxios from './plugins/axios'

Vue.use(VueAxios)

Now, you can use axios as this.$axios in your components. So something like this.$axios.get().

Therefore, you can import axios with the following line:

import { axios } from '@/plugins/axios'

Now, you can use axios directly in your store.

Or you can also use it as Vuex plugin:

import { axios } from '@/plugins/axios'

const axiosPlugin = store => {
   store.$axios = axios
}

new Vuex.Store({
    ...,
    plugins: [axiosPlugin]
})

Now, you can use it as this.$axios in Vuex.


Vue.use means adding plugins. However, axios is not a plugin for Vue, so you can not add it globally via use.

My recommendation is importing axios only when you need it. But if you really need to access it globally, you may like to add it to prototype.

Vue.prototype.$axios = axios

Then you can access axios in vue using this.$axios