Синхронные HTTP-запросы в Node.js

У меня есть три компонента A, B а также C, когда A отправляет HTTP-запрос B, B отправляет еще один HTTP-запрос Cизвлекает относительное содержимое и отправляет его обратно A, как ответ HTTP.

B Компонент представлен следующим фрагментом Node.js.

var requestify = require('requestify');

// sends an HTTP request to C and retrieves the response content
function remoterequest(url, data) {
  var returnedvalue;
  requestify.post(url, data).then(function(response) {
    var body = response.getBody();
    // TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
  });
  return returnedvalue;
}

// manages A's request
function manageanotherhttprequest() {
  // [...]
  var res = remoterequest(url, data);
  // possible elaboration of res
  return res;
}

Мне нужно вернуться body содержание в результате remoterequest функция. Я замечаю, что в настоящее время запрос POST является асинхронным. Следовательно returnedvalue переменная никогда не присваивается до возвращения ее вызывающему методу.

Как я могу выполнить синхронные HTTP-запросы?

2 ответа

Ты используешь restify который вернется promise однажды его вызвали для его методов (post, get..так далее). Но метод, который вы создали remoterequest не возвращается promise вам ждать, используя .then, Вы можете сделать это, чтобы вернуться promise с помощью async-await или встроенный promise как показано ниже:

  • используя обещание:

    var requestify = require('requestify');
    
    // sends an HTTP request to C and retrieves the response content
    function remoterequest(url, data) {
      var returnedvalue;
      return new Promise((resolve) => {
        requestify.post(url, data).then(function (response) {
          var body = response.getBody();
          // TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
        });
        // return at the end of processing
        resolve(returnedvalue);
      }).catch(err => {
        console.log(err);
      });
    }
    
    // manages A's request
    function manageanotherhttprequest() {
      remoterequest(url, data).then(res => {
        return res;
      });
    }
    
  • используя async-await

    var requestify = require('requestify');
    
    // sends an HTTP request to C and retrieves the response content
    async function remoterequest(url, data) {
    
      try {
        var returnedvalue;
        var response = await requestify.post(url, data);
        var body = response.getBody();
        // TODO use body to send back to the client the number of expected outputs, by setting the returnedvalue variable
        // return at the end of processing
        return returnedvalue;
      } catch (err) {
        console.log(err);
      };
    }
    
    // manages A's request
    async function manageanotherhttprequest() {
        var res = await remoterequest(url, data);
        return res;
    }
    

Вы можете отправлять синхронные HTTP-запросы с помощью sync-request-curl — библиотеки, которую я написал в 2023 году.

Он содержит подмножество функций исходного запроса синхронизации , но использует node-libcurl для повышения производительности в NodeJS.

Простой HTTP-запрос GET можно записать следующим образом:

      // import request from 'sync-request-curl'; // for ESM
const request = require('sync-request-curl');
const response = request('GET', 'https://ipinfo.io/json');
console.log('Status Code:', response.statusCode);
console.log('body:', response.body.toString());

В вашем случае вашу функцию можно переписать синхронно следующим образом:

      const request = require('sync-request-curl');

// sends an HTTP request to C and retrieves the response content
function remoterequest(url, data) {
  const response = request('POST', url, { json: data });

  if (response.statusCode === 200) {
    return JSON.parse(response.body.toString());
  } else {
    // handle error
  }
}

// manages A's request
function manageanotherhttprequest() {
  // [...]
  const res = remoterequest(url, data);
  // possible elaboration of res
  return res;
}

Надеюсь это поможет :).

Другие вопросы по тегам