简体   繁体   English

在POST请求触发之前,如何获取GET请求的响应主体的内容? 能做到这一点吗?

[英]How do I get the contents of the response body of a GET request before the POST request fires? Can this be done with promise?

So I'm receiving a JSON object from the front-end and sending it to my backend to the endpoint /getData. 因此,我从前端接收JSON对象,并将其发送到后端的端点/ getData。 Here, I use a GET request to obtain data from an API and I need to send both the JSON object and the GET response body in the final POST request. 在这里,我使用GET请求从API获取数据,并且需要在最终的POST请求中发送JSON对象和GET响应主体。 But when I send the request, the body of the GET response comes in too late and "formInfo" is undefined. 但是,当我发送请求时,GET响应的主体来不及,并且“ formInfo”未定义。

How do I fix this so the POST request sends once the GET is fulfilled? 如何解决此问题,以便GET完成后发送POST请求?

 app.post('/getData', function(req, res) {
    debugger;
    var data = req.body;
    console.log(data);
    toSend = data;
    res.send({msg: "Success"});
    var findID = {};
    var endPoint = 'https://secure.p01.eloqua.com/API/REST/2.0/assets/form/' + toSend["formID"].toString();
    var options = {
        method: "GET",
        headers: {'Authorization': authenticationHeader, 'Content-Type': 'application/json'}
    };
    request.get(endPoint, options, function (error, response, body) {
        console.log(body);
        findID = body["elements"];
            request({
                    method: "POST",
                    headers: {'content-type': 'application/json', 'authorization': authenticationHeader},
                    url: 'http://localhost:3000/handleData',
                    json: {
                        "tuples": toSend,
                        "formInfo": body['elements']
                    }},
                function (error, response, body) {
                    console.log(response);
                });
    });
});

Have you considered using the fetch API ? 您是否考虑过使用fetch API

It's widely supported in modern browsers - and you can transpile it worst case - and NodeJS. 它在现代浏览器中得到广泛的支持 -您甚至可以将其转换为最糟糕的情况-以及NodeJS。

With it you'd be able to chain requests, eg 有了它,您就可以链接请求,例如

fetch(`first.url.com`)
  .then(response => 
    fetch(`second.url.com`, {body: response.body})
  )

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

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