问题
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!
- 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
回答1:
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
回答2:
I found a solution. Add this code in your: /src/main.js
Example:
const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
Vue.axios.defaults.baseURL = baseURL;
}
The answer that helped me in this: Set baseURL from .env in VueAxios
Thanks everyone for help!
来源:https://stackoverflow.com/questions/48597306/dynamic-host-in-axios