Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic host in axios

How can I create a dynamic host in axios?

Example:

 const host = location.hostname;
 // axios.defaults.baseURL = 'http://hastore.local';
 axios.defaults.baseURL = host;
 axios.defaults.port = 8080;
 axios.get('api/categories')
 .then((res) => {
      this.categories = res.data;
      console.log(res);
 })
 .catch((err) => {
      console.warn('error during http call', err);
 });

String axios.defaults.baseURL = 'http://hastore.local'; does not fit, because on prodaction don't be work.

String const host = location.hostname; also not a solution, because I get incorrect port and dublicate host.

enter image description here

The goal is to get the right host depending on the environment. I read a lot of articles about this, but I did not find a solution. Thanks for help!

  • axios version: e.g.: v0.16.2
  • Environment: e.g.: node v8.9.4, chrome 64.0.3282.119, Ubuntu 16.04
  • Symfony 4.0.4
  • Vue.js 2.4.2
  • vue-axios 2.0.2
like image 346
Dmitry S. Avatar asked Mar 07 '23 23:03

Dmitry S.


1 Answers

You probably do not need to set baseURL. Have you tried to define baseURL each time you make requests? For example,

axios.get(`${host}:${port}/api/categories`)

Or, depending on your words "The goal is to get the right host depending on the environment.", you may define proper host using your environment variables, for example:

axios.get(`${proccess.env.HOST}:${PORT}/api/categories`)

If you use a bundler for your frontend code, this expression will be resolved to

axios.get('http://example.com:80/api/categories')

That's because your bundler actually should run with pre-defined environment variables HOST and PORT

like image 187
Akhmedzianov Danilian Avatar answered Mar 11 '23 05:03

Akhmedzianov Danilian