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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24912226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:40:48  来源:igfitidea点击:

How to make Ajax request through NodeJS to an endpoint

ajaxnode.jsq

提问by SharpCoder

I am using NodeJS. One of my function (lets call it funcOne) receives some input which I pass to another function (lets call it funcTwo) which produces some output.

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

Before I pass the input to funcTwo I need to make an Ajax call to an endpoint passing the input and then I must pass the output produced by the AJAX call to funcTwo. funcTwo should be called only when the AJAX call is successful.

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

How can I achieve this in NodeJS. I wonder if Q Librarycan be utilized in this case

如何在 NodeJS 中实现这一点。我想知道在这种情况下是否可以使用Q Library

回答by Bar?? U?akl?

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

回答by arthurakay

Why not use the NodeJS https.request()API?

为什么不使用NodeJS https.request()API?

(Or http.request()if you didn't need HTTPS)

(或者http.request()如果您不需要 HTTPS)