axios 中的动态主机 [英] Dynamic host in axios
问题描述
如何在 axios
中创建动态主机?
示例:
const host = location.hostname;//axios.defaults.baseURL = 'http://hastore.local';axios.defaults.baseURL = 主机;axios.defaults.port = 8080;axios.get('api/categories').then((res) => {this.categories = res.data;控制台日志(res);}).catch((错误) => {console.warn('http 调用出错', err);});
String axios.defaults.baseURL = 'http://hastore.local';
不适合,因为在生产中不起作用.
String const host = location.hostname;
也不是解决方案,因为我得到了不正确的端口和重复的主机.
目标是根据环境获得合适的主机.我阅读了很多关于此的文章,但我没有找到解决方案.感谢帮助!
- axios 版本:例如:v0.16.2
- 环境:例如: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
您可能不需要设置 baseURL.您是否尝试在每次发出请求时都定义 baseURL?例如,
axios.get(`${host}:${port}/api/categories`)
或者,根据您所说的目标是根据环境获得合适的主机.",您可以使用环境变量定义合适的主机,例如:
axios.get(`${proccess.env.HOST}:${PORT}/api/categories`)
预>
如果您为前端代码使用捆绑器,则此表达式将解析为
axios.get('http://example.com:80/api/categories')
那是因为你的打包器实际上应该使用预定义的环境变量 HOST
和 PORT
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
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
这篇关于axios 中的动态主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!