繁体   English   中英

将http请求中的数据保存到数组中,以json的形式发送回客户端

[英]Save data from http request into an array, to send it as json back to the client

我有一个执行API请求的node.js服务器,该页面应将我从该api获取的数据作为响应发送。 这里的收获是:

我需要对api进行多次调用,将所有数据放在一起,并用id分隔,然后将其作为json发送回客户端。

要创建该请求,我首先要查询我的数据库并获取要发送到api的数据。之后,我使用array.filter过滤数据并创建请求,然后使用array.map调用一个处理交易的函数与请求。

码:

router.get('/', cors(),  (req, res) =>{

    const response =  getListOfStatistics()
 });

当我进入页面时,功能getListOfStatistics()被触发:

function getListOfStatistics(){
    axios.get('http://localhost:4002/')
    .then(response =>{
        items = response.data
        let result = filterStatistic(items)
        return result;
        //I wrote that return result when trying to give the data back
        //So I could send it to the client as json

    })
    .catch(err =>{
        console.log(err)
    })    

}

从数据库获取数据后,我尝试对其进行过滤:

function filterStatistic(items){

const jahreStatistic = items.filter(item => item.period == 0)
const virtelJahrStatistic = items.filter(item => item.period == 3)

//Both methods above are working

jahreStatistic.map(item => {
    connection.statistic_id = item.statistic_id
    var periods = getReportingPeriod(item.period)
    for(let i=0; i < 3; i++){
        switch(i){
            case 0:
            connection.reporting_period = periods.prevYear
            preOrderedObjects.Jahr =  sendHTTPRequest(item)
            break;
            case 1:
            connection.reporting_period = periods.actualYear
            preOrderedObjects.Jahr =   sendHTTPRequest(item)
            break;
            case 2:
            connection.reporting_period = periods.nextYear
            preOrderedObjects.Jahr =   sendHTTPRequest(item)
            break;
         }
        }
    })
}


function  sendHTTPRequest (item){

request.post({
    headers: {'content-type' : 'application/x-www-form-urlencoded'},
    url: 'https://externalapi/api/', 
    form: connection
    },
    (err, response, body) => {
        if(response.headers['x-status'])
        {
            info.name = item.name
            info.evas = item.evas
            info.id = item.statistic_id
            info.link = item.link
            info.resourceID = response.headers['x-resourceid'];
            info.fileName = response.headers['x-filename'];

            console.log(info.name) //This shows that my three requests 
            were made.

            **if(item.period==0){
                //Evas is a global array evas = []
                //info is a global object info = {}
                evas.push(info)
                //My goal was to push each request to this array and 
                //return it to after, add to another object.
                //This does not work.
                return evas**
            }else{
                ids.push(info)
                preOrderedObjects.Jahr = ids
            }
            }
    }) 
}

我想将所有数据推送到evas数组,然后添加到我的preOrderedObjects.Jahr

之后,最后,我想将其作为json返回给客户端

任何人都知道我缺少什么,以及如何解决?

您需要将getListOfStatistics函数转换为回调函数 您正在使用Promise (可以说是更好的回调版本)向另一台服务器发出GET请求,并且结果可能需要一段时间才能获得值。

一旦有值,回调将返回result变量。

function getListOfStatistics(callback){
    axios.get('http://localhost:4002/')
    .then(response =>{
        items = response.data
        let result = filterStatistic(items)
        callback(result);
    })
    .catch(err =>{
        console.log(err)
    })
}

要执行getListOfStatistics ,您将需要传递一个函数作为参数,如下所示:

let response;
getListOfStatistics(function(result)){
    response = result;
}

请注意response必须是一个变量,并且在回调完成后将具有一个值。

sendHTTPRequest方法也是如此,由于您希望所有请求都完成,因此您也需要对其进行转换。 但是,使用EvaspreOrderedObjects作为全局变量看起来不是一个好主意,但是无论如何。

function filterStatistic(items, callback){

const jahreStatistic = items.filter(item => item.period == 0)
const virtelJahrStatistic = items.filter(item => item.period == 3)

//Both methods above are working

jahreStatistic.map(item => {
    connection.statistic_id = item.statistic_id
    var periods = getReportingPeriod(item.period)
    for(let i=0; i < 3; i++){
        switch(i){
            case 0:
            connection.reporting_period = periods.prevYear
            sendHTTPRequest(item, function(result){
              preOrderedObjects.Jahr =  result
            })
            break;
            case 1:
            connection.reporting_period = periods.actualYear
            sendHTTPRequest(item, function(result){
              preOrderedObjects.Jahr =  result
            })
            break;
            case 2:
            connection.reporting_period = periods.nextYear
            sendHTTPRequest(item, function(result){
              preOrderedObjects.Jahr =  result
            })
            break;
         }
        }
    })
}


function  sendHTTPRequest (item, callback){

request.post({
        headers: {'content-type' : 'application/x-www-form-urlencoded'},
        url: 'https://externalapi/api/', 
        form: connection
    },
    (err, response, body) => {
        if(response.headers['x-status'])
        {
            info.name = item.name
            info.evas = item.evas
            info.id = item.statistic_id
            info.link = item.link
            info.resourceID = response.headers['x-resourceid'];
            info.fileName = response.headers['x-filename'];

            console.log(info.name) //This shows that my three requests 
            were made.

            **if(item.period==0){
                evas.push(info)                
                callback(evas)
            }else{
                ids.push(info)
                preOrderedObjects.Jahr = ids
            }
         }
    }) 
}

好吧,对于初学者来说,您可以尝试将请求标头更改为:“ application / json”。

至于请求,它们是异步的,因此您不能立即获得结果,可以将getListOfStatistics转换为回调或对函数调用async / await技巧,如下所示:

function getListOfStatistics(){
    axios.get('http://localhost:4002/')
    .then(async (response) =>{
        items = response.data
        let result = await filterStatistic(items);

        return result;
    })
    .catch(err =>{
        console.log(err)
    });

对于该开关/案例,您也正在发出http异步请求,可以使用async await方法,也可以将请求推送到promise数组中并立即解决它们:

let requests = [];

jahreStatistic.map(item => {
    connection.statistic_id = item.statistic_id
    var periods = getReportingPeriod(item.period)
    for(let i=0; i < 3; i++){
        switch(i){
            case 0:
            connection.reporting_period = periods.prevYear
            requests.push(sendHTTPRequest(item));
            break;
            case 1:
            connection.reporting_period = periods.actualYear
            requests.push(sendHTTPRequest(item));
            break;
            case 2:
            connection.reporting_period = periods.nextYear
            requests.push(sendHTTPRequest(item));
            break;
         }
        }
    })
}

Promise.all(requests).then((results) => {
 // do some work here
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM