【问题标题】:Dynamic host in axiosaxios中的动态主机
【发布时间】:2018-02-03 12:21:46
【问题描述】:

如何在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 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

【问题讨论】:

标签: symfony vue.js axios symfony4


【解决方案1】:

您可能不需要设置 baseURL。您是否尝试在每次发出请求时定义 baseURL?例如,

axios.get(`${host}:${port}/api/categories`)

或者,根据您所说的“目标是根据环境获得正确的主机。”,您可以使用您的环境变量定义正确的主机,例如:

axios.get(`${proccess.env.HOST}:${PORT}/api/categories`)

如果您对前端代码使用捆绑器,则此表达式将被解析为

axios.get('http://example.com:80/api/categories')

那是因为您的打包程序实际上应该使用预定义的环境变量 HOSTPORT 运行

【讨论】:

  • 是的,我每次发出请求时都需要尝试定义 baseURL。
  • 使用环境变量是个好主意,但我不确定我是否可以访问它们。 @AchmedzianovDanilian
  • 我得到undefined何时在控制台打印console.log(process.env.HOST);
  • 当然,您必须在调用 build 之前定义环境变量。如果你调用的变量没有定义,你会得到 undefined。
【解决方案2】:

我找到了解决方案。将此代码添加到您的:/src/main.js

例子:

const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
  Vue.axios.defaults.baseURL = baseURL;
}

对我有帮助的答案:Set baseURL from .env in VueAxios

感谢大家的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2022-11-08
    • 2013-06-24
    • 2014-02-26
    • 1970-01-01
    相关资源
    最近更新 更多