knot22
knot22

Reputation: 2768

define base URL globally in Axios plugin for Vue

In my Vue.js project, I have created a plugin for Axios using the instructions from here so that Axios will be available globally in the project. The pertinent code in my project looks like this:

in src/plugins/axios.js -

import axios from 'axios';

export default {
  install: function(Vue) {
    Object.defineProperty(Vue.prototype, '$axios', { value: axios });
  }
}

in src/main.js -

import axios from './plugins/axios';
Vue.use(axios);

new Vue({
  render: h => h(App),
  created() {
    console.log(this.$axios ? 'axios plugin works' : 'axios plugin does not work');
  }
}).$mount('#app');

The console is outputting axios plugin works so all is well to this point.

In a file that uses Axios, there are several hard coded URLs. Shown below is just one example of a method from the file:
src/forms/official-scenarios.vue -

export default {
    data() {
        return {
                errors: [],
                officialScenarios: []                
        }
    },
    methods: {
        getOfficialScenarios() {
            this.$axios
            .get('https://localhost/myapp/api/scenariolog')
            .then(response => {
                this.officialScenarios = response.data;
            })
            .catch(error => {
                this.errors.push(error);
            });
        }
    },
    mounted: function () {
        this.getOfficialScenarios(); 
    },
}

What I'd like to do is define a base URL globally for https://localhost/myapp/api and reference that in each method that uses this.$axios. How that that be defined? Then what does the usage look like in official-scenarios.vue?

Upvotes: 6

Views: 19368

Answers (4)

Oddman
Oddman

Reputation: 3959

For anyone who is seeing this in Vue 3, I took the above accepted answer and changed it slightly:

import axios from 'axios'

const instance = axios.create({
    baseURL: 'myapp/api/'
});

export default Vue => Vue.provide('$axios', instance)

You can also if wanting to configure your URL based on environment (good idea), is to use environment variables to do exactly that. So you could instead of having 'myapp/api/', you could (when using vite), instead use:

import.meta.env.VITE_AXIOS_BASE_URL

Hope that helps :)

Upvotes: 0

knot22
knot22

Reputation: 2768

I ended up modifying src/plugins/axios.js as follows -

import axios from 'axios';

const instance = axios.create({
    baseURL: 'myapp/api/'
});

export default {
  install: function(Vue) {
    Object.defineProperty(Vue.prototype, '$axios', { value: instance });
  }
}

Since Axios supports relative paths, https://localhost/ was stripped out of the baseURL string.

Then usage in getOfficialScenarios() method src/forms/official-scenarios.vue became this -

getOfficialScenarios() {
    this.$axios
    .get('scenariolog')
    .then(response => {
        this.officialScenarios = response.data;
    })
    .catch(error => {
        this.errors.push(error);
    });
}

Upvotes: 2

ScottyG
ScottyG

Reputation: 3410

You can set the base URL in the axios object itself. It should look something like:

// Set base URL
axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';

Upvotes: 5

Ignacio
Ignacio

Reputation: 116

Maybe you can use a .env files and call it with a globaly var in vue or in the store (vuex), like API_URL: process.env.API_URL and this.$store.state.API_URL (or getter)

Check this

You can also create a axios instance and use it

Check this

Regards!

Upvotes: 1

Related Questions