【问题标题】:Testing a simple GET request from NodeJS测试来自 NodeJS 的简单 GET 请求
【发布时间】:2018-06-26 03:56:27
【问题描述】:

出于测试目的,我想在服务器创建后立即调用一个方法(执行 GET 请求)。我有以下代码。

var rp = require('request-promise');
var http = require('http');

var URLSplunk = MY_URL

var headersSplunk = {
    'Authorization': 'Bearer MY_AUTH',
    'Cache-Control': 'no-cache',
    'X-Requested-By': 'BABEL_FISH',
    'client': 'slack'
};

function testSplunk(){
  var optionsSplunk = {
      url: URLSplunk,
      headers: headersSplunk,
      json: true
  };

  rp(optionsSplunk)
      .then(function (resultReply) {
        console.log("Splunk GET success")
        console.log(resultReply)
      })
      .catch(function (error) {
          console.log(`Error: \n${error}`);
      });

}

http.createServer(function (request, response) {
    testSplunk()
}).listen(3000);

console.log('Server started');

我期待看到 GET 结果或错误,但我只看到“Server started”消息。

我错过了什么?

【问题讨论】:

  • 试着把 testSplunk();在创建服务器功能之后。
  • 你现在拥有代码的方式,你的testSplunk() 函数只会在你的http服务器收到请求时被调用。它在 http 服务器 requestListener 回调中。因此,您必须向 http 服务器发送一个请求以触发该回调,以便调用 testSplunk() 函数。目前尚不清楚您是否希望它以这种方式工作,但这就是您当前的代码将要做的事情。
  • @Philip556677 谢谢它的工作。如果您将其作为答案,我会将其标记为答案。

标签: node.js httprequest


【解决方案1】:

@jfiend00 更详细地回应了我的评论。

按照您现在拥有代码的方式,您的 testSplunk() 函数只会在您的 http 服务器收到请求时被调用。它在 http 服务器 requestListener 回调中。因此,您必须向 http 服务器发送请求以触发该回调,以便调用 testSplunk() 函数。

在向服务器发出请求之前,程序永远不会调用 testSplunt() 函数。

将它放在 requestListener 回调之后将允许它以您希望的方式执行。

例如

http.createServer(function (request, response) {
    //This function is called when the server gets a request
    //Process request.......
}).listen(3000);

testSplunk();

console.log('Server started');

【讨论】:

    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 2021-04-25
    • 2021-03-12
    • 2021-07-16
    • 1970-01-01
    • 2019-12-26
    • 2015-07-25
    • 2016-03-19
    相关资源
    最近更新 更多