In a small Vue application I'm working on there is code like this:
this.axios.post('https://localhost:8000/api/auth/login',.......).
The https://localhost:8000 needs to change after deploying to a server since the server side of the application will be hosted at a different IP address/port. I want to define something like a BASE_URL that can be read from a configuration file or something like that, which means the above code would change to something like:
this.axios.post(`${BASE_URL}/api/auth/login`)
What's the best way to do this within Vue.js? Initially baseUrl sounded promising, but that doesn't seem to be what I need.
You can use environment variables to define your base url. For example, create files .env.development and .env.production at the base of your project:
VUE_APP_BASE_URL=https://localhost:8000
Then, you can specify the base url as part of the axios config:
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
The vue application will change depending what mode you use to build, for example npm run build -- --mode development or npm run build -- --mode production
You can create a .env file in your root, and reference that: https://cli.vuejs.org/guide/mode-and-env.html#modes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With