当有多个页面时,如何使用axios获取所有响应数据?

时间:2020-03-05 07:22:06

标签: node.js get axios

我有一个像{"page":1,"per_page":10,"total":99,"total_pages":10,"data":[object1, object2, object3,...]} 这样的URL,可以给我:

axios.get("https://abc123.com/api/records?&page=2")
  .then(response => console.log(response.data))
{"page":2,"per_page":10,"total":99,"total_pages":10,"data":[object1, object2, object3,...]}

然后给我类似

{{1}}

我想从所有10个页面访问“数据”中的所有对象。我该如何使用nodeJS和axios?

1 个答案:

答案 0 :(得分:0)

您可以使用诸如do ... while之类的循环来下载每页数据。检索完最后一页数据后,我们将停止下载。

我们使用params对象设置page参数,从第1页开始。

const axios = require("axios");

// Replace with the appropriate url.
const url = "https://abc123.com/api/records"

async function downloadRecords() {

    let records = [];
    let page = 0;
    let totalPages = 0;

    do {
        let { data: response }  = await axios.get(url, { params: { page: ++page } });
        totalPages = response.total_pages;
        console.log(`downloadRecords: page ${page} of ${totalPages} downloaded...`);
        records = records.concat(response.data);
        console.log("records.length:", records.length);
    } while (page < totalPages)

    console.log("downloadRecords: download complete.")
}

downloadRecords();