【问题标题】:Correctly duplicating a JS object when building multiple GET requests (with Axios)构建多个 GET 请求时正确复制 JS 对象(使用 Axios)
【发布时间】:2020-07-09 16:11:02
【问题描述】:

下面是一个 sn-p,它通过多次请求检索前 N 页数据,在 HackerNews api 中搜索关键字“java”

理想情况下,它应该检索数据集的前 3 页:

https://hn.algolia.com/api/v1/search_by_date?query=java&page=0
https://hn.algolia.com/api/v1/search_by_date?query=java&page=1
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2

这里是代码,also available as a CodePen

// Fetch all HackerNews posts with the search string 'java'
const url = 'https://hn.algolia.com/api/v1/search_by_date';

const config = {
  headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
  params: { query: 'java', page: null }
};

const numPagesToFetch = 3;

// Build a series of requests, one for each page
let requests = [];
for (var i = 0; i < numPagesToFetch; i++) {
  
  // Duplicate the `config` object for each request
  let requestCfg = Object.assign({}, config);

  // The only `param` changing for each request is `?page=`
  // HN API starts numbering from page 0
  requestCfg.params.page = i;

  console.log(`Generating request for page ${requestCfg.params.page}`);
  requests.push(axios.get(url, requestCfg));
}

// Wait on all requests to complete in parallel, then handle the output
Promise.all(requests).
  then((responses) => {
    // Should be equal to numPagesToFetch (3)
    console.log(`Number of responses: ${responses.length}`);

    for(var i = 0; i < responses.length; i++) {
      // Print out some info about each response
      const firstId = responses[i].data.hits[0].story_id;
      const requestUrl = responses[i].request.responseURL;
      console.log(`Dataset Response from ${requestUrl} starts with id ${firstId}`);
    }
  }).
  catch(error => {
    console.log('There was an error');
  })

当我运行它时,它似乎多次检索同一页面(最后一页)

https://hn.algolia.com/api/v1/search_by_date?query=java&page=2
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2

我觉得这与 JS 或 axios 如何处理对变量的引用有关。当我构建每个请求并增加page 时,它会影响使用相同变量构造的所有其他请求。我什至注意“复制”config 对象,但它没有帮助。

知道为什么它会发出 3 次相同的请求吗?

谢谢!

【问题讨论】:

    标签: javascript object get axios


    【解决方案1】:

    这是因为你没有深度克隆它,你只是克隆了根对象,但内部对象仍然指向它们的原始对象......你可以使用https://www.npmjs.com/package/clone-deep 或者使用这个将它转换为字符串的小技巧然后解析为对象:

    let requestCfg = JSON.parse(JSON.stringify(config));
    

    【讨论】:

    • 非常感谢!这终于解决了我两天来一直试图解决的问题:)
    • 很高兴能帮到你???
    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 2021-09-11
    • 2021-10-26
    • 1970-01-01
    • 2021-09-12
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多