首页 > 解决方案 > 使用 promise.all() 获取 ID 数组不起作用

问题描述

我正在使用 promise.all() 发出一系列 api 请求,以根据对象的 id 返回对象。但是,我得到了 404,我认为这是由于我添加标题的方式(因为我尝试使用另一个不需要身份验证的更简单的 API 并且它工作正常)。

我正在访问的 API 是 UDEMY api。此处的文档:https ://www.udemy.com/developers/affiliate/

谁能帮我用标题完成这项工作?谢谢。

getCourseData = () => {
  let courseIDs = this.state.beginnerCourseIDs;
  
  let headers = new Headers();
  headers.append('Authorization', 'Basic ' + base64.encode("XXUSERKEY:XXSECRETKEY"))

  let requests = courseIDs.map(course => { 
    return fetch(`https://cors-anywhere.herokuapp.com/https://www.udemy.com/api-2.0/courses/${course}/, { headers: ${headers} }` )
  });

  Promise.all(requests)
  .then(responses => responses.forEach(
    response => console.log(response)
  ));
}

标签: reactjsfetchrequest-promise

解决方案


目前,您的 headers 对象正在形成您的 url 字符串的一部分。

您需要将标题添加到 options 对象,即fetch的第二个参数:

let requests = courseIDs.map(course => { 
  return fetch(`https://cors-anywhere.herokuapp.com/https://www.udemy.com/api-2.0/courses/${course}/`, { headers })
});

此外,如果 API 返回 JSON,那么您需要将响应解析为 JSON 对象:

let requests = courseIDs.map(course => { 
  return fetch(`https://cors-anywhere.herokuapp.com/https://www.udemy.com/api-2.0/courses/${course}/`, { headers })
    .then(res => res.json())
});

希望这可以解决您的问题。


推荐阅读