【问题标题】:Making multiple Axios get requests with an array of links?使用一系列链接制作多个 Axios 获取请求?
【发布时间】:2021-06-21 22:07:52
【问题描述】:

我有一个函数,我想为学生返回所有即将完成的作业。我首先运行另一个异步函数,该函数返回学生在一个学期和一年内的所有课程 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 并同时进行调用。虽然我有点难过,但我是否只需要为.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))

【问题讨论】:

  • 代码看起来正确并且应该可以工作,您面临的问题是什么。你需要更具体
  • @Sohan 我面临的问题是 axios.all([urls]) 返回UnhandledPromiseRejectionWarning: Error: Request failed with status code 401。我无法弄清楚为什么我不能从每个 url 调用中返回正确的数据。我将其缩小为我如何设置axios.all 呼叫的问题。
  • 它是401。看起来远程端点是安全的,并且您没有在 Authorization 标头中传递有效令牌?请先验证一下?还要用您遇到的错误更新您的问题。它提供了更多上下文
  • @Sohan 这是我忘记添加到通话中的内容。感谢您注意到这一点!我现在只需要让axios.all 获取数组中的每个链接。我会根据我的问题更新我的帖子。

标签: javascript arrays promise axios


【解决方案1】:

假设你已经创建了你的 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({......});

【讨论】:

  • 谢谢!我现在已经正确设置了我的标题,但我仍然遇到axios.all 不会运行我的数组中的每个 url 的问题。它返回错误TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received an instance of Array。我不知道如何遍历我的 urls[] 数组以让 axios.all 运行
  • 您已经拥有url []。你为什么要通过[urls]。检查我的更新答案
  • @OrangeCry 如果这对你有用,你能否也支持这个答案
猜你喜欢
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多