【问题标题】:http.request post method not responding with no error on callbackhttp.request post 方法没有响应,回调没有错误
【发布时间】:2016-11-01 15:09:56
【问题描述】:

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

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

}
});

【问题讨论】:

  • 我不知道为什么(还),但我建议查看 h2o2 插件:github.com/hapijs/h2o2 它是作为 hapi.js 的代理处理程序,应该正是您需要的(请参阅使用部分)
  • Hapi 生态系统提出Wreck 来处理HTTP 请求。然而,调试感兴趣的是调用/apipath:2000所执行的代码。

标签: node.js http-post httprequest hapijs


【解决方案1】:

您看不到任何错误或响应,因为您正在流式传输响应并在 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();

...
... 

正如 cmets 中所说,您还有其他用于在 hapi 中发出 http 请求的模块

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多