Home > Mobile >  fetching in express js with axios returns [Object object]
fetching in express js with axios returns [Object object]

Time:03-14

I have another api that lets say returns this given a query name using a get request

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

for example

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

I'm now using express to create another API that fetches on that API but it can take more than one friend as input. e.g. https:/localhost:5000/api?names=bob,sam, this would output total friends being 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 });
}

it returns

{
    friends:[Object Object] 
}

instead?

CodePudding user response:

first, if you just need number of friends, then simply return the total, why are you pushing it again to total_friends... total already does the job

second thing I would suggest while looping and performing async operation is to promisify the entire for loop first, you can do this using http://bluebirdjs.com/docs/api/promise.each.html

CodePudding user response:

Your problem is that you are using res.send(...). I think what you are actually wanting is res.json(...).

res.send(...) just uses the toString method of the object you are putting in to it. res.json(...) will convert your object to JSON.

  • Related