axios中的动态主机 [英] Dynamic host in axios
问题描述
如何在axios
中创建动态主机?
How can I create a dynamic host in axios
?
示例:
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);
});
字符串axios.defaults.baseURL = 'http://hastore.local';
不适合,因为在生产过程中不起作用.
String axios.defaults.baseURL = 'http://hastore.local';
does not fit, because on prodaction don't be work.
字符串const host = location.hostname;
也不是解决方案,因为我得到了错误的端口并复制了主机.
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版本:例如:v0.16.2
- 环境:例如:节点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
推荐答案
您可能不需要设置baseURL.您是否在每次发出请求时都尝试定义baseURL?例如,
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')
那是因为您的捆绑程序实际上应与预定义的环境变量HOST
和PORT
That's because your bundler actually should run with pre-defined environment variables HOST
and PORT
这篇关于axios中的动态主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!