2016-11-01 61 views
0

我想对我的电脑中另一个端口上运行的REST API进行POST调用。 http.get方法工作正常,但是当我发出一个POST请求时,服务器返回任何响应或回调中的任何错误。这里是我的代码:http.request 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); 
     }); 
    }); 

} 
}); 
+0

我不知道为什么(还),但我会建议看H2O2插件:https://github.com/hapijs/ h2o2 它意味着作为hapi.js的代理处理程序,并且应该正是您所需要的(请参阅我们年龄部分) – tgo

+0

Hapi生态系统建议[Wreck](https://github.com/hapijs/wreck)处理HTTP请求。但是,调试有趣的是通过调用'/ apipath:2000'执行的代码。 –

回答

0

你是无法看到任何错误或响应,因为你是你的流媒体响应并结束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(); 

... 
... 

正如评论说你作出的HTTP请求高致病性禽流感等模块