Web Services Node.js中的同步HTTP请求

kmpatx3s  于 2023-10-24  发布在  Node.js
关注(0)|答案(2)|浏览(164)

我有三个组件ABC。当AB发送HTTP请求时,BC发送另一个HTTP请求,检索相关内容并将其作为HTTP响应发送回A
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请求?

rvpgvaaj

rvpgvaaj1#

您正在使用restify,它将在调用其方法(postget ..等)时返回promise。但是您创建的remoterequest方法不会返回promise,您可以使用.then等待。您可以使用async-await或内置的promise返回promise,如下所示:

  • 使用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;
  });
}
  • 使用等待
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;
}
yhxst69z

yhxst69z2#

你可以使用sync-request-curl发送同步HTTP请求,这是我在2023年编写的一个库。

它包含了原始sync-request中的一部分功能,但利用了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;
}

希望这对你有帮助:)

相关问题