首页 > 解决方案 > 如何根据动态创建的请求数组执行多个axios get请求

问题描述

我正在尝试学习 Angular/node & express。我目前正在尝试为我的支持编写一个端点

  1. 需要使用 axios 向外部 API 运行 get 请求,该 API 将返回 ID 列表(数字)
  2. 对于提供的每个 ID,运行一个请求,根据该 ID 获取详细信息。

但我的问题是关于2 号的。我有一个 ID 列表作为输入,我想根据每个 ID 运行对外部 API(使用 axios)的请求。请注意 - 基于 ID 对外部 API 的请求会返回一个包含该 ID 详细信息的对象,因此我的 API 端点的总体目标是返回一个对象数组,其中每个对象都包含标识。

有几个和我类似的问题...

  1. 将 axios 请求的响应推送到数组中(这与我的问题非常相似)
  2. axios 随机请求数

但是,他们使用的是 React.js,我很难将他们的解决方案调整为 node/express。

我正在尝试根据第一个问题的顶部提供的代码片段来模拟我的方法。但是,我的解决方案是返回一个空对象作为响应。

我的问题:我可以做些什么不同的事情来向外部 API 发出多个 axios GET 请求,其中每个请求都是动态创建的

app.route('/test').get((req, res) => {
    axios
        .get('https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=vodka')//This will not be hardcoded, but grabbed as a parameter from the endpoint
        .then(function(response) {
            //Purpose of this initial .then() clause is to make a call to the cocktaildb API to get the IDs of all the cocktails with a given ingredient eg: vodka.

            var data = response.data;//response.data contains the JSON object containing the contents received by the cocktaildb API request.
            var cocktailIds = [];

            //collect all cocktail ids so we can later make more requests to obtain the details associated with that ID.
            data.drinks.forEach(drink => {
                cocktailIds.push(drink['idDrink']);
            });

            //this is passed on to the next then clause. It is a list of cocktail ids.
            return cocktailIds;
        })
        .then((drinks) => {
            //the promises variable contains a list of all the requests we will have to make in order to get the details of all cocktail ids. I have tested that they are valid requests.
            const promises = drinks.map(id => {
                //console.log(getCocktailDetailsUrl + id);
                return axios.get(getCocktailDetailsUrl + id)
                .then(({data}) => {
                    return data;
                })
            })
            
            //I was hoping Promise.All to execute all of the requests in the promise and response to be stored in the cocktailDetails variable
            const cocktailDetails = Promise.all(promises)
            .then(values => {
                return values;
            })
            .catch(error => {
                console.log("There was an error when sending requests for details of all cocktails");
                console.log(error);
            })

            //Sending response only formatted this way for testing purposes
            if(cocktailDetails) {
                //this block is executed, and an empty object is returned as response
                console.log("cocktails was sent as response");
                res.send(cocktailDetails);
            } else {
                console.log("cocktails was not sent as response");
                res.send("cocktailDetails was not poppulated at the time of sending response");
            }
        })
        .catch(function (error) {
            res.send("There was an iswsue with your request to the cocktaildb API.");
            console.log('The following is the error from the request to the cocktaildb API: ' + error);
        })
});

正如我之前提到的,我的响应包含一个空对象。我知道我必须以某种方式使用 promise.all,但我不确定如何正确实现它。

标签: node.jsexpresspromiseaxios

解决方案


您的问题是在发送响应之前您没有等待所有承诺解决。额外的批评,您的代码可以大大简化为以下内容:

app.route('/test').get((req, res) => {
    axios.get('https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=vodka')//This will not be hardcoded, but grabbed as a parameter from the endpoint
    .then(function(response) {

        const promises = response.data.drinks.map(drink =>axios.get(getCocktailDetailsUrl + drink.idDrink).then(({data})=>data));

        //I was hoping Promise.All to execute all of the requests in the promise and response to be stored in the cocktailDetails variable
        return Promise.all(promises)
        .then(values => {
            res.send(values);// shouldn't you be using res.json() here?
        });//if an error is thrown for any reason here, it will be caught by your outer catch 
    })
    .catch(function (error) {
        res.send("There was an iswsue with your request to the cocktaildb API.");
        console.log('The following is the error from the request to the cocktaildb API: ' + error);
    });
});

推荐阅读