Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: global base URL of server side application

Tags:

vue.js

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.

like image 968
Chris Avatar asked Oct 22 '25 03:10

Chris


2 Answers

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

like image 73
Andrei Savin Avatar answered Oct 23 '25 20:10

Andrei Savin


You can create a .env file in your root, and reference that: https://cli.vuejs.org/guide/mode-and-env.html#modes

like image 42
Sweet Chilly Philly Avatar answered Oct 23 '25 21:10

Sweet Chilly Philly