Set baseURL from .env in VueAxios

风流意气都作罢 提交于 2019-12-01 10:16:23

问题


I am using a standard Vue starer webpack template with VueAxios installed. I want to configure axios using .env variable when building with dev command. I have everything set up within /config/index.js:

const devEnv = require('./dev.env')
module.exports = {
...
    host: devEnv.host || 'localhost',
    port: devEnv.port || 8080,
...
}

Then I define my host and port in dev.env.js in the same directory and it all works fine.

const dotenv = require('dotenv').config({path: '../.env'})

let host = process.env.VUE_HOST;
let port = +process.env.VUE_PORT;

module.exports = merge(prodEnv, {
    NODE_ENV: '"development"',
    host,
    port
})

But the problem is that I can't access host value within src/main.js of my Vue app.

If I try to do it like this I get an error that

vue is not defined

import axios from 'axios'
import VueAxios from 'vue-axios'
...
Vue.use(VueAxios, axios)
Vue.axios.defaults.baseURL = `http://${process.env.host}:${process.env.port}`;

Though the port works fine, the host does not and throws an error.


回答1:


UPDATE for Vue CLI 3

All you need to do now is just set VUE_APP_BASE_URL in your .env file. Then you'll be able to access it like this:

process.env.VUE_APP_BASE_URL

But an even better solution would be to configure a dev server.


Previous solution

Solution was quite simple:

  • Define a special variable for that case within webpack.dev.conf.js plugins, omit using process.env for that.

    new webpack.DefinePlugin({
        'process.env': require('../config/dev.env'),  // You can't use this for baseURL
        'baseURL': JSON.stringify(`http://${HOST || config.dev.host}:${PORT || config.dev.port}`)
    }),
    
  • In \src\main.js define it like this:

    if (typeof baseURL !== 'undefined')
    {
        Vue.axios.defaults.baseURL = baseURL;
    }
    



回答2:


The answer above helped me. But I want to make an amendment. In /src/main.js need define constant.

Example:

const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
  Vue.axios.defaults.baseURL = baseURL;
}

Also don't need to add code in file webpack.dev.conf.js. Although maybe this is only suitable for my problem.

My problem: Dynamic host in axios



来源:https://stackoverflow.com/questions/48205273/set-baseurl-from-env-in-vueaxios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!