Set baseURL from .env in VueAxios

巧了我就是萌 提交于 2019-12-01 13:34:43

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

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

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