Dmi*_* S. 6 symfony vue.js axios symfony4
如何在 中创建动态主机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);
});
Run Code Online (Sandbox Code Playgroud)
字符串axios.defaults.baseURL = 'http://hastore.local';不适合,因为在生产中不起作用。
字符串const host = location.hostname;也不是解决方案,因为我得到了不正确的端口和重复的主机。
目标是根据环境找到合适的主机。我读了很多关于这个问题的文章,但没有找到解决方案。感谢帮助!
您可能不需要设置 baseURL。您是否尝试在每次发出请求时都定义baseURL?例如,
axios.get(`${host}:${port}/api/categories`)Run Code Online (Sandbox Code Playgroud)
或者,根据您的话“目标是根据环境获得正确的主机。”,您可以使用环境变量定义正确的主机,例如:
axios.get(`${proccess.env.HOST}:${PORT}/api/categories`)Run Code Online (Sandbox Code Playgroud)
如果您对前端代码使用捆绑器,则此表达式将解析为
axios.get('http://example.com:80/api/categories')Run Code Online (Sandbox Code Playgroud)
这是因为您的捆绑程序实际上应该使用预定义的环境变量运行HOST,并且PORT
| 归档时间: |
|
| 查看次数: |
37216 次 |
| 最近记录: |