簡體   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