2016-11-01 12 views
0

自分のPCの別のポートで実行している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

にHTTPリクエストを行うための他のモジュールを持っているコメントで言いましたh2o2 これはhapi.jsのプロキシハンドラとしての意味であり、必要なものでなければなりません(Us age section) – tgo

+0

Hapiエコシステムでは、HTTPリクエストを処理するための[Wreck](https://github.com/hapijs/wreck)が提案されています。しかし、デバッグに興味深いのは '/ apipath:2000'の呼び出しによって実行されるコードです。 –

答えて

0

あなたはあなたの応答をストリーミングし、http.request内の要求を終了しているので、あなたはすべてのエラーまたは応答を見ることができません()ここで、それはこのようにする必要がありますよう...

https://github.com/hapijs/:
... 
... 
... 

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

... 
... 

としては、必ず理由を(まだ)ないですが、私はH2O2のプラグインを見てお勧めしますあなたはHAPI

関連する問題