'axios base url from local json file

Tried to load baseURL for axios from local json file and export in variable "http" for use in applications. Tried to different way to implemetntation.Pls help

import axios from "axios";

const getURL = async () => {
    const resp = await axios.get('/config.json');
    return  axios.create({
        baseURL: resp.data.url,
    });
};
export const http = getURL();


Solution 1:[1]

You could try with .env files https://cli.vuejs.org/guide/mode-and-env.html

Solution 2:[2]

If you're using vue-cli, then this would work for you:

Inside main.js file (this is entry point):

import axios from 'axios'

/**
 * config.json implementation
 */
let axiosInstance = null

;(async () => {
  try {
    const config = await axios.get('/config.json')
    axiosInstance = axios.create({
      baseURL: config?.data?.url || 'some-fallback-url'
    })
  } catch (err) {
    console.warn('Error!', err)
  } finally {
    Vue.prototype.$http = axiosInstance

    new Vue({
      router,
      store,
      render: h => h(App),
    }).$mount('#app')
  }
})()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mapr
Solution 2 Alexander Kim