javascript - 使用一系列链接制作多个 Axios 获取请求?
问题描述
我有一个功能,我想为学生返回所有即将完成的作业。我首先运行另一个异步函数,该函数返回学生在一个学期和一年内的所有课程 ID。然后我用每个类的 .get url 填充一个数组。
我的问题是理解和使用Axios.all()
,因为我想对每个班级进行多次调用,然后对每个作业进行排序,只保存迟于学生当前日期到期的作业。我面临的问题是axios.all([urls])
返回UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
。我无法弄清楚为什么我不能从每个 url 调用中返回正确的数据。我将其缩小为我如何设置 axios.all 调用的问题。有人可以指出我正确的方向吗?
//Get all upcoming assignments from each class for a user
async function getAssignments(){
//Make multiple requests to api
axios
.all([urls])
//Loop through each assignment for each class
.then(
axios.spread((...res) =>{
for (var i = 0; i < res.data.length; i++) {
//If the due date of the assignment is due later than the users current date, push to array
if (res.data[i]['due_at'] > date.toISOString()) {
assignments.push(res.data[i])
}
}
//Output all assignments
return assignments
})
)
}
更新:
我忘记将令牌传递给我的标头,经过更多调整后,它现在将从我的数组中获取指定的 url。但我现在需要它来抓取数组中的每个 url 并同时进行调用。虽然我有点难过,但我只需要为 the.get
或更具体的东西制作一个 for 循环吗?有人可以指出我正确的方向吗?
//urls is the array filled with links. Need for the axios calls to happen concurrently
axios.all([axios.get(
urls[0],
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)])
//Loop through each assignment in a specfied class in canvas
.then(
axios.spread((...res) =>{
for (var i = 0; i < res[0].data.length; i++) {
//If the due date of the assignment is due later than the users current date, push to array
if (res[0].data[i]['due_at'] > date.toISOString()) {
assignments.push(res[0].data[i])
}
}
console.log(assignments)
})
)
.catch((err) => console.log(err))
解决方案
假设您已经创建了 axios 实例,您可以在最初在 axios 实例级别设置标题,您可以简单地,
const axios = require('axios');
axios.defaults.headers.common['Authorization'] = 'Bearer AUTH_TOKEN';
//Get the course ID for each class the user is assigned to
const courseID = await getCurrentCourses('Spring', '2021')
//Fill the array with urls to each course assignment page
for(let i = 0; i < courseID.length; i++){
urls.push(axios.get('https://example.com/api/v1/courses/' + allCourseID[i] + '/assignments'));
}
//Make multiple requests to api
axios.all(urls)
//Loop through each assignment for each class
.then({......});
推荐阅读
- python - 如何在不收到错误消息的情况下导入 tensorflow?
- powerbi - Power BI - 从同一行中减去值
- python - 'tee' 不是内部或外部命令、可运行程序或批处理文件
- java - Java 将图像附加到 JTextArea
- angular - Angular 9 单元测试业力
- python - 如何使用 matplotlib 让图例显示在图表中
- java - 在文本中搜索 REGEX 值
- c++ - CUDA:让内核将函数指针作为参数
- bezier - Inkscape 自动平滑节点背后的算法
- javascript - 数据方法中的数组在一种方法中得到更新,但在另一种方法中仍然为空