nodeJs如何执行http发布请求

问题描述 投票:0回答:1

我将问题的范围缩小了,我想将发布请求发送到API服务器,但是发布请求仅在程序退出后才发送。我的main.js:

var request = require("request");
send_post_to_server = function(name, responseCallback, outconfig) {
    var outconfig = outconfig || {...};
    request.post({
        url: 'http://localhost:3000/api/backtest',
        json: outconfig
    }, function optionalCallback(error, response, body) {
        responseCallback(error, response, body);
    });
}

send_post_to_server ('first post request', my_response_callback);
send_post_to_server ('second post request', my_response_callback);
while(true); // with the loop, the server never gets the post requests.

[如果我删除了while循环而程序退出,则它会起作用,并且确实会收到对optionalCallbackresponseCallback的响应。但是使用循环,服务器无法获得请求。为什么会这样?以及如何使程序发送请求?冲洗吗?运行我使用的程序:请求模块的node main.jsnpm istall request

javascript node.js request http-post
1个回答
0
投票

因为while(true);使用单个线程阻止了线程和Node.js。首选异步执行操作。另请参阅:https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

如果您想让Node.js进程不终止,则有一个答案How to forcibly keep a Node.js process from terminating?

© www.soinside.com 2019 - 2024. All rights reserved.