简体   繁体   English

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

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

I have a node.js server that does an API request, the page should send as response the data I get from that api. 我有一个执行API请求的node.js服务器,该页面应将我从该api获取的数据作为响应发送。 The catch here is: 这里的收获是:

I need to do several calls to the api, put all the data together separated by an id e send that back as json to the client. 我需要对api进行多次调用,将所有数据放在一起,并用id分隔,然后将其作为json发送回客户端。

To create that request I have first to query my DB and get the data I have to send to the api After that I filter that data using array.filter and to create the requests, I am using array.map to call a function that deals with the request. 要创建该请求,我首先要查询我的数据库并获取要发送到api的数据。之后,我使用array.filter过滤数据并创建请求,然后使用array.map调用一个处理交易的函数与请求。

Code: 码:

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

    const response =  getListOfStatistics()
 });

when I enter the page, the function getListOfStatistics() is fired: 当我进入页面时,功能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)
    })    

} }

After getting the data from the db, I try filtering it: 从数据库获取数据后,我尝试对其进行过滤:

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
            }
            }
    }) 
}

I would like to get all the data pushed to the evas array and then added to my preOrderedObjects.Jahr 我想将所有数据推送到evas数组,然后添加到我的preOrderedObjects.Jahr

After, at the end, I want to return that to the client as json 之后,最后,我想将其作为json返回给客户端

Anyone has an idea of what I am missing and how to maybe fix that? 任何人都知道我缺少什么,以及如何解决?

You need to convert your getListOfStatistics function into a callback function . 您需要将getListOfStatistics函数转换为回调函数 You are making a GET request to another server using promises (we can say a better version of callbacks) and the result might take a while to have a value. 您正在使用Promise (可以说是更好的回调版本)向另一台服务器发出GET请求,并且结果可能需要一段时间才能获得值。

The callback will return the result variable once it has a value. 一旦有值,回调将返回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)
    })
}

To execute getListOfStatistics , you will need to pass a function as a parameter, like this: 要执行getListOfStatistics ,您将需要传递一个函数作为参数,如下所示:

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

Note that response must be a variable and it will have a value once the callback is finished. 请注意response必须是一个变量,并且在回调完成后将具有一个值。

Same goes for sendHTTPRequest method, you will need to convert it too since you want all requests to finish. sendHTTPRequest方法也是如此,由于您希望所有请求都完成,因此您也需要对其进行转换。 However using Evas and preOrderedObjects as global variables don't look like a good idea, but anyways. 但是,使用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
            }
         }
    }) 
}

Well, for starters you can try to change the request headers to: 'application/json'. 好吧,对于初学者来说,您可以尝试将请求标头更改为:“ application / json”。

As for the requests, they are async, so you cannot get the result immediately, you can turn the getListOfStatistics into a callback or call the async/await trick on the function as follows: 至于请求,它们是异步的,因此您不能立即获得结果,可以将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)
    });

As for that switch/case, you are also making http async requests, you can use the async await method OR you can push the requests into a promise array and resolve them all at once: 对于该开关/案例,您也正在发出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.

相关问题 另存为PDF:建议使用服务器解决方案从客户端接收原始数据并将PDF发送回客户端吗? - save as PDF: recommend a server solution to receive raw data from client and send back PDF to client? NodeJS/ExpressJS - 将 http 请求的响应发送回客户端 - NodeJS/ExpressJS - Send response of http request back to client 尝试将数据从客户端发送到服务器时,POST http://localhost:3000/data 400(错误请求) - POST http://localhost:3000/data 400 (Bad Request) when trying to send data from client to server 为什么php json响应不会将数据数组发送回给ajax jquery请求? - Why php json response does not send back the data array to ajax jquery request? 如何在 vanilla Nodejs 中将 JSON 数据发送回客户端 - How to send JSON data back to client in vanilla Nodejs JSON的主干FETCH,编辑模型数据,然后保存回JSON - Backbone FETCH from JSON, edit model data then SAVE back to JSON 需要将数据从NodeJS服务器发送回JQuery客户端 - Need to send data back from a NodeJS server to a JQuery client 将数据从 node.js 发送回客户端 javascript - Send back data from node.js to client side javascript 如何将POST请求中的JSON发送给客户端? - How can I send the JSON coming from a POST request to the client? 使用Node.js从客户端向服务器发送json请求 - use Node.js to send a json request from client to the server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM