如何在POST请求触发之前获取GET请求的响应正文的内容? 这可以用承诺来完成吗?

所以我从前端接收一个JSON对象,并把它发送到我的后端到端点/ getData。 在这里,我使用GET请求从API获取数据,并且需要在最终的POST请求中同时发送JSON对象和GET响应正文。 但是,当我发送请求时,GET响应的主体来得太晚,“formInfo”未定义。

如何解决这个问题,以便POST请求一旦GET完成发送?

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

你有没有考虑过使用fetch API ?

它在现代浏览器中得到了广泛的支持 – 而且你可以将其最糟糕的情况和NodeJS进行传输。

有了它,你可以链接请求,例如

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