【问题标题】:Why i get Error 500 fetching data with axios为什么我使用 axios 获取数据时出现错误 500
【发布时间】:2020-05-15 09:35:06
【问题描述】:

我正在做一个小项目来学习并将它放在我的项目部分 我遇到这样的问题:

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

未捕获(承诺中)错误:请求失败,状态码为 500 在 createError (createError.js:16) 定居时 (settle.js:17) 在 XMLHttpRequest.handleLoad (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); 
}

【问题讨论】:

  • 如果您仍然有该错误,请添加该函数的完整代码以及您调用它的至少部分代码。
  • 这是我调用提取的代码export async function fetchData(text) { const proxy = cors-anywhere.herokuapp.com; const base = recipepuppy.com/api?; const baseEnd = q=${text}; const data = await axios.get(${proxy}${base} ?${baseEnd}).catch(err =&gt; console.log(err)); console.log(data) return recipes.length &gt; 0 ? recipes : false; } 这是我调用函数的地方 `
  • 这就是我调用我的函数async function getRecipes(e){ e.preventDefault(); const text = e.target[1].value; const loader = '&lt;div class="loader"&gt;&lt;/div&gt;'; container.insertAdjacentHTML('beforebegin', loader); const recipes = await fetchData(text); document.querySelector('.loader').remove(); displayRecipes(recipes); }
  • 这是 2 天前的工作,昨天我想编写我的小应用程序,但它甚至没有获取数据
  • 所以错误指向至少 3 个脚本。可能你是从另一个异步函数调用 getRecepies() 并且它也包含在 Promise 中?就在几天前,我与 Vuejs 中的授权流程作斗争并遇到了同样的错误。所以为了本地化它,我将所有逻辑移到“根”函数中,然后开始将部分代码移动到相关的“子”函数中。问题在某种程度上缺少 .catch()。

标签: javascript async-await xmlhttprequest axios httprequest


【解决方案1】:

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

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

【讨论】:

  • try {await axios.get(${proxy}${base}?${baseEnd})} catch(err){console.log(err)} -- 知道为什么没有使用 await 处理。
猜你喜欢
  • 2021-11-05
  • 1970-01-01
  • 2021-07-20
  • 2019-10-12
  • 2020-12-07
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2019-11-24
相关资源
最近更新 更多