【问题标题】:How should i use .then and .catch in an axios call in Vue JavaScript App?我应该如何在 Vue JavaScript App 的 axios 调用中使用 .then 和 .catch?
【发布时间】:2019-06-09 17:25:56
【问题描述】:

我在安装在 Vue 应用程序中调用此代码

mounted() {
this.isMounted = true;

axios.get('https://randomuser.me/api/').then((response) => {
  console.log("Response is" + response)

}).catch(function(error) {
  // handle error
  console.log("Error is: " + error);
})

}

并且总是得到相同的错误:错误:请求失败,状态码为 404

我已经测试过 API 并且运行良好,总是以 200 响应。 我不知道我做错了什么

【问题讨论】:

  • 你确定是https吗?
  • 是的,它的 https,问题是 MockAdapter

标签: vue.js promise vuejs2 axios


【解决方案1】:

我发现了错误。 我已经激活了一个模拟适配器,所以每个调用都由这个 MockAdapter 处理。

var mock = new MockAdapter(axios);

因此,如果不在 mockCalls 列表中,则每个调用都会失败。 有没有办法让 MockAdapter 只用于某些特定的调用?例如,您必须使用两个不同的 API,并且只想模拟其中一个

【讨论】:

    【解决方案2】:

    试试这个代码。

    mounted () {
        this.isMounted = true;
        axios
          .get('https://api.coindesk.com/v1/bpi/currentprice.json')
          .then(response => {
            console.log("Response is" + response)
          })
          .catch(error => {
            console.log(error)
    
          })
      }
    

        mounted () {  
        axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                  .then(function (response) {
                   console.log("Response is" + response)
                  }.bind(this))
                  .catch(error => {
                    console.log(error)
                  })
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2022-06-12
      • 2016-10-01
      • 2020-01-28
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多