简体   繁体   English

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

[英]How to make Ajax request through NodeJS to an endpoint

I am using NodeJS.我正在使用 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.我的一个函数(我们称之为 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 之前,我需要对传递输入的端点进行 Ajax 调用,然后我必须将 AJAX 调用产生的输出传递给 funcTwo。 funcTwo should be called only when the AJAX call is successful.只有在 AJAX 调用成功时才应调用 funcTwo。

How can I achieve this in NodeJS.如何在 NodeJS 中实现这一点。 I wonder if Q Library can be utilized in this case我想知道在这种情况下是否可以使用Q Library

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

Edit: Since request is now deprecated you can find alternatives here编辑:由于 request 现在已弃用,您可以在此处找到替代方案

Why not use the NodeJS https.request() API? 为什么不使用NodeJS https.request() API?

(Or http.request() if you didn't need HTTPS) (如果你不需要HTTPS,可以是http.request()

Since request is deprecated.由于请求已被弃用。 I recommend working with axios.我建议使用 axios。

npm install axios@0.16.2

const axios = require('axios');

axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
  .then(response => {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error => {
    console.log(error);
  });

Using the standard http library to make requests will require more effort to parse/get data.使用标准的 http 库发出请求将需要更多的努力来解析/获取数据。 For someone who was used to making AJAX request purely in Java/JavaScript I found axios to be easy to pick up.对于习惯于纯粹使用 Java/JavaScript 发出 AJAX 请求的人,我发现 axios 很容易上手。

https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM