http.request post 方法没有响应且回调没有错误

http.request post method not responding with no error on callback

我想在我电脑的另一个端口上对我的 REST API 运行 进行 POST 调用。 http.get 方法工作正常,但是当我发出 POST 请求时,服务器 returns 没有响应或回调中出现任何错误。这是我的代码:

server.route({
method:'POST',
path:'/path1',
handler: function(req, res){
    var post_data = querystring.stringify({
        'name': 'asd',
        'price': '123'
    });
    var options = {
        host: '127.0.0.1',
        port: 2000,
        path: '/apipath',
        method:'POST',
        header:{
            'Content-Type':'application/json',
            'Content-Length': Buffer.byteLength(post_data)
        }
    };


     var post_req = http.request(options, function(reply){
            console.log('222');
            reply.setEncoding('utf8');
            reply.on('data', function (body) {
                console.log('Body: ' + body);
        });
        post_req.write(post_data);
        post_req.end();
        res(reply);
        post_req.on('error', function(e) {
        console.error(e);
        });
    });

}
});

您看不到任何错误或响应,因为您正在流式传输您的响应并在 http.request() 中结束请求,它应该是这样的...

...
...
...

var post_req = http.request(options, function(reply){
    console.log('222');
    reply.setEncoding('utf8');
    reply.on('data', function (body) {
        console.log('Body: ' + body);
    });            
});

post_req.on('error', function(e) {
    console.error(e);
});

post_req.write(post_data);
post_req.end();

...
... 

如评论中所述,您还有其他模块可以在 hapi 中发出 http 请求