提问者:小点点

为什么我得到错误500获取数据与axios


我正在做一个小项目来学习,并把它放在我的项目部分,我有这样的问题:

收到https://cors-anywhere.herokuapp.com/http://www.recipepuppy.com/api/?q=rice500(内部服务器错误)

未捕获(promise)错误:请求失败,状态代码500在createError(createError.js:16)在解决(settle.js:17)在XMLHttpRequest.handle加载(xhr.js:61)

我尝试使用axios头(我在另一个论坛上找到了这个建议,但它不起作用)我获取数据的代码看起来像这样

 export async function fetchData(text) {
    const proxy = `https://cors-anywhere.herokuapp.com/`;
    const base = `http://www.recipepuppy.com/api/`;
    const baseEnd = `q=${text}`;
    const data = await axios
      .get(`${proxy}${base}?${baseEnd}`)
      .then(data =>console.log(data));
    const recipes = data.data.results;
    return recipes.length > 0 ? recipes : false;
  }

此处调用的函数:

async function getRecipes(e){ 
  e.preventDefault(); 
  const text = e.target[1].value; 
  const loader = '<div class="loader"></div>'; 
  container.insertAdjacentHTML('beforebegin', loader); 
  const recipes = await fetchData(text); 
  document.querySelector('.loader').remove(); 
  displayRecipes(recipes); 
}

共1个答案

匿名用户

您需要从Promise捕获可能的错误(如axios.get()返回Promise类型对象)。

axios.get(`${proxy}${base}?${baseEnd}`)
  .then(data =>console.log(data))
  .catch(error => {
    console.log(error)
  })