【问题标题】:Not data on new array poolList when use axios, but console.log still have data使用axios时新数组poolList上没有数据,但是console.log还有数据
【发布时间】:2022-01-11 07:03:28
【问题描述】:

我在使用 axios 创建 API 时遇到了麻烦。新数组没有收到包含数据,但是当我运行 console.log(response) 时,它会显示数据(参见图片附件)。任何人都可以帮助我解决这个问题

router.get('/', async (req, res) => {
    const pools = [
        'pool1',
        'pool2',
    ]
    const poolList = pools.map(async pool => {
        const response = await axios.get(`https://example.com/pools/${pool}/summary.json`)
        console.log(response)
        return {
            response
        }
    })
    res.send({
        poolList
    })
})

enter image description here

【问题讨论】:

  • 试试Promise.all(poolList).then(res.send)。您可能还希望在地图回调中使用return response.data
  • 我试过你的评论,但仍然是同样的问题

标签: node.js api express axios


【解决方案1】:

问题

您的poolList 是一系列承诺。然后,您尝试将这些承诺作为 JSON 进行响应。这看起来像下面这样,因为当 Promise 被字符串化时,它们变成了空对象

{
  "poolList": [{}, {}]
}

解决方案

我怀疑你真正想要的是以下......

router.get('/', async (req, res) => {
  const pools = [
    'pool1',
    'pool2',
  ]

  try {
    const poolList = await Promise.all(pools.map(async pool => {
      const { data } = await axios.get(`https://example.com/pools/${encodeURIComponent(pool)}/summary.json`)
      return data // resolve with the data, not the full Response object
    }))

    res.json({ poolList })
  } catch (err) {
    console.error(err)
    res.status(500).send(err)
  }
})

这会创建一个用远程数据(每个summary.json)解析的承诺数组,并等待每个承诺,从而产生一个数据数组。

这会以类似的方式响应

{
  "poolList": [
    { /* pool1/summary.json */ },
    { /* pool2/summary.json */ }
  ]
}

【讨论】:

  • 返回404错误如下{message: "Request failed with status code 404"} message: "Request failed with status code 404"
  • @TADA 这可能意味着您的至少一个summary.json URL 不正确
  • 是的,我明白了,非常感谢菲尔,你的建议很棒:3
【解决方案2】:

这是因为 pools.map(async pool => { 中的异步。预期的 poolList 的结果是一个 promise 数组。

尝试等待所有

const pools = [
    'pool1',
    'pool2',
]
const poolList = await Promise.all(pools.map(async pool => {
    const response = await axios.get(`https://example.com/pools/${pool}/summary.json`)
    console.log(response)
    return {
        response
    }
}));


res.send({
    poolList
})

【讨论】:

  • 我试过你的评论,但它仍然是同样的问题:((
猜你喜欢
  • 2018-01-18
  • 2021-10-26
  • 2022-01-11
  • 1970-01-01
  • 2018-08-20
  • 2019-04-26
  • 2014-05-13
  • 2020-04-14
  • 1970-01-01
相关资源
最近更新 更多