reactjs - 使用 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)
));
}
解决方案
目前,您的 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())
});
希望这可以解决您的问题。
推荐阅读
- r - R:如何在方法中设置成员变量?
- java - 在 JavaFX 中将节点的形状和大小绑定到剪贴蒙版
- python - 在函数中使用全局变量而不将其显式传递给函数时是否可能会收到警告?
- c++ - 模块 (DLL) 的类大小不同。如何以及为什么?
- mysql - 相同的 ID 不同的值变成一行
- c# - 为什么我在mysql中的count命令返回错误的值-1?
- kubernetes - 在 Kubernetes 中实现 WebSocket 时出错
- javascript - 错误未知类型“webform__webform”使用 gatsby-drupal-webform & GraphQL
- spring-boot - Primefaces+SpringBoot大文件上传失败
- php - Xpath,在html代码中查找节点的位置