【问题标题】:Showing warning when API returns empty data (Vue.js / Axios)当 API 返回空数据时显示警告(Vue.js / Axios)
【发布时间】:2021-01-08 22:03:01
【问题描述】:

我对 Vue.js 和 Axios 很陌生。我正在通过搜索功能从 API 获取和显示数据,并试图弄清楚如何显示警告/警报或让用户知道 API 响应为空的内容。

观察结果:当搜索框中有匹配项时应用显示数据,但没有完全匹配时不显示任何内容

预期结果:当没有完全匹配时在前端显示文本或警报以指示“没有匹配”

      
      axios.get(`API LINK HERE`,

    {
headers: {
      "x-rapidapi-host":"API HOST LINK HERE",
    "x-rapidapi-key":"API KEY HERE",
    "useQueryString":true
    },"params":{
    "format":"json",
    "date-format":"YYYY-MM-DD",
    "name":`${query}`

}
    })
    
      .then(response => this.itemData = response.data)
        
    }```

【问题讨论】:

  • itemData 是一个数组吗?
  • @mbesuma 请更新您的代码,以便它在您的问题中的格式正确且便于人们阅读。

标签: javascript api vue.js axios


【解决方案1】:

只需使用条件语句检查任何结果。

.then(response => {if (response.data=="") {// code here to alert user of empty response }})

您可以将this.itemData 设置为表示空响应的消息或使用其他一些提醒用户的方法。

【讨论】:

    【解决方案2】:

    我对 Vue.js 不太熟悉,但我认为这更多的是关于 javascript,你可以这样做:

        axios.get(`API LINK HERE`, { headers: HEADERS})
          .then(res => {
              if (isEmpty(res.data) {
                  alert("is empty");
              } else {
                  this.itemData = response.data;
              }
          })
          .catch(error => alert("problem. try later")) // your error handling
    

    如果你喜欢更多尝试和捕捉:

    try {
        const res = await axios.get(`API LINK HERE`, { headers: HEADERS});
        const itemData = res.data;
        if (isEmpty(itemData) {
            alert("is empty");
        } else {
            this.itemData = itemData;
        }
    } catch (error) {
        alert("my error handling");
    }
    

    【讨论】:

    猜你喜欢
    • 2019-06-07
    • 2020-04-08
    • 2018-08-05
    • 1970-01-01
    • 2021-02-05
    • 2019-12-16
    • 2019-04-01
    • 2019-03-11
    • 2020-10-26
    相关资源
    最近更新 更多