在 Vue 的 Axios 插件中全局定义基本 URL

kno*_*t22 6 javascript vue.js axios

在我的 Vue.js 项目中,我使用此处的说明为 Axios 创建了一个插件,以便 Axios 在项目中全局可用。我的项目中的相关代码如下所示:

在 src/plugins/axios.js 中 -

import axios from 'axios';

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

在 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');
Run Code Online (Sandbox Code Playgroud)

控制台正在输出,axios plugin works所以到目前为止一切都很好。

在使用 Axios 的文件中,有几个硬编码的 URL。下面显示的只是文件中的一种方法的示例:
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(); 
    },
}
Run Code Online (Sandbox Code Playgroud)

我想做的是在全局范围内定义一个基本 URL,https://localhost/myapp/api并在每个使用this.$axios. 那如何定义呢?那么 中的用法是什么样的呢official-scenarios.vue

Sco*_*tyG 5

您可以在 axios 对象本身中设置基本 URL。它应该看起来像:

// Set base URL
axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
Run Code Online (Sandbox Code Playgroud)


kno*_*t22 2

我最终修改了src/plugins/axios.js如下 -

import axios from 'axios';

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

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

由于 Axios 支持相对路径,https://localhost/因此被剥离了 baseURL 字符串。

然后getOfficialScenarios()方法src/forms/official-scenarios.vue中的用法变成了这样 -

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