如何在 POST 请求触发之前获取 GET 请求的响应正文的内容?这能不能有希望地完成



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

如何解决此问题,以便在 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);
                });
    });
});

您是否考虑过使用 fetch API?

它在现代浏览器中得到广泛支持 - 您可以在最坏的情况下转译它 - 和 NodeJS。

有了它,您将能够链接请求,例如

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

相关内容

最新更新