如何在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';不适合,因为对于prodaction不工作。
String const host = location.hostname;也不是一个解决方案,因为我得到了错误的端口和错误的主机。

目标是根据环境获得正确的主机。我读了很多关于这方面的文章,但我没有找到解决办法。谢谢你帮忙!
发布于 2018-02-03 12:35:40
您可能不需要设置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运行。
发布于 2018-02-03 13:47:11
我找到了解决办法。将此代码添加到您的:/src/main.js中
示例:
const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
Vue.axios.defaults.baseURL = baseURL;
}在这方面帮助我的答案是:Set baseURL from .env in VueAxios
谢谢大家的帮助!
https://stackoverflow.com/questions/48597306
复制相似问题