gpt4 book ai didi

node.js - 测试来自 NodeJS 的简单 GET 请求

转载 作者:搜寻专家 更新时间:2023-10-31 23:57:23 36 4
gpt4 key购买 nike

出于测试目的,我想在创建服务器后立即调用一个方法(执行 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”消息。

我错过了什么?

最佳答案

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

The way you have the code now, your testSplunk() function will get called only when your http server gets a request. It's inside the http server requestListener callback. So, you have to send the http server a request to trigger that callback so the testSplunk() function gets called.

在向服务器发出请求之前,程序永远不会调用 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');

关于node.js - 测试来自 NodeJS 的简单 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51034653/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com