如何获取https响应的正文 [英] How to get the body of https response

查看:119
本文介绍了如何获取https响应的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Office.js进行编程.我正在尝试读取从服务器获取的数据. Https.get一定要送达达! (我将其打印一秒钟,然后再将其从服务器发送回去,并获得200码). 问题是我无法从服务器获取数据并打印或进行一些计算.

I am doing programming in Office.js. I'm trying to read the data which I get from the server. Https.get return the dada for sure! (I print it one second before sending it back from the server and also get a 200 code). The issue is that I am not able to take the data I got from server and print it or o some calculations with it.

我到处都在寻找答案,但是由于某种原因,它无法正常工作.

I looked for an answer everywhere but it just doesn't work for some reason I don't get.

var request = https.get("https://localhost:8888/getLastDetailedOrders", function(response){

                            //console.log(response.statusCode); //Testing the response.
                            //read the data
                            response.on('data', function (chunk){
                                body += chunk;
                              });
                            //ending the event.
                            response.on('end', function() {
                                range2.values = [[body]];
                                console.log(body); // prints nothing! 
                                console.log('No more data in response.');
                            })
                        });

请帮助我读取数据并对其进行处理

Please help me to read the data and treat it

推荐答案

我知道存在比赛条件. 我在其中编写https请求的officejs异步函数只是在服务器有时间发回信息并由客户端捕获信息之前就结束了它的工作. 即使有回叫,由于Office需要上下文参数,而且由于功能已终止,所以这里不再存在,客户端无法处理服务器返回的信息. 因此解决方案是在我将放置https请求的地方创建一个新的异步函数,该函数返回一个Promise. 然后从主函数调用新函数,方法是在调用之前先添加await.然后,在调用之后执行.then()以完成主函数的所有其余任务. 这样,您可以强制main函数等待,直到我们获得服务器的完整响应.

I inderstood that there was a race condition. The async function of officejs in which i wrote the https request simply ended its work before the server had the time to send back the information and the client to catch it. Even though there was a call back, since office needs the context paramater and it was not here any more because the function had been ended, the client could nt do any thing with the information being returned by the server. So the solution was to make a new async function where i would put the https request, this function return a promise. Then from the main function call the new function by adding await first before the call. Then .then() after the call to do all the rest tasks of the main function. This way you force the main function to wait until we get the full response from the server.

这篇关于如何获取https响应的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆