如何通过 NodeJS 向端点发出 Ajax 请求

2023-12-31

我正在使用 NodeJS。我的一个函数(我们称之为 funcOne)接收一些输入,我将其传递给另一个函数(我们称之为 funcTwo),该函数产生一些输出。

在将输入传递给 funcTwo 之前,我需要对传递输入的端点进行 Ajax 调用,然后必须将 AJAX 调用产生的输出传递给 funcTwo。仅当 AJAX 调用成功时才应调用 funcTwo。

我怎样才能在 NodeJS 中实现这一点。我怀疑是否Q库 https://github.com/kriskowal/q在这种情况下可以使用


Using request https://github.com/request/request

function funcOne(input) { 
  var request = require('request');
  request.post(someUrl, {json: true, body: input}, function(err, res, body) {
      if (!err && res.statusCode === 200) {
          funcTwo(body, function(err, output) {
              console.log(err, output);
          });
      }
  });
}

function funcTwo(input, callback) {
    // process input
    callback(null, input);
}

编辑:由于请求现已被弃用,您可以找到替代方案here https://github.com/request/request/issues/3143

您还可以使用最新版本的 nodejs(18+) 附带的内置 fetch API。请参阅下面的示例。

async function funcOne(input) {
  try {
    const response = await fetch(someUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(input),
    });

    if (response.ok) {
      const body = await response.json();
      funcTwo(body, (err, output) => {
        console.log(err, output);
      });
    }
  } catch (err) {
    // Handle errors here
    console.error(err);
  }
}

function funcTwo(input, callback) {
  // process input
  callback(null, input);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过 NodeJS 向端点发出 Ajax 请求 的相关文章

随机推荐