使用 axios returns [Object object] 在 express js 中获取

fetching in express js with axios returns [Object object]

我有另一个 api 可以说 returns 这给定了一个使用 get 请求的查询名称

https://another_api.com/?name=${name}

例如

>>> https://another_api.com/?name=bob
{
    friends: [10]
}
>>> https://another_api.com/?name=sam
{
    friends: [4]
}

我现在正在使用 express 创建另一个 API 来获取那个 API 但它可以接受多个朋友作为输入。例如https:/localhost:5000/api?names=bob,sam,这将输出好友总数为 14

app.get("/api", async (req, res) => {
    const names = req.query.names;


    const names_array = names.split(",");
    

    let total_friends = [];
    let total = 0
    for (const name of names_array) {
        const response = await axios.get(`https://another_api.com/?name=${name}`);
        const friends = response.data.friends[0];
        total += friends
    }
    total_friends.push(total)
    res.send({ "friends": total_friends });
}

它returns

{
    friends:[Object Object] 
}

代替?

您的问题是您正在使用 res.send(...)。我认为您真正想要的是 res.json(...).

res.send(...) 只是使用您要放入其中的对象的 toString 方法。 res.json(...) 会将您的对象转换为 JSON.

首先,如果你只需要朋友的数量,那么只需 return total,你为什么要再次将其推到 total_friends... total完成任务

在循环和执行异步操作时我建议的第二件事是首先 promisify 整个 for 循环,你可以使用 http://bluebirdjs.com/docs/api/promise.each.html