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.
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!
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
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