node.js POST请求失败

我试图用node.js执行一个POST请求,但似乎总是超时。 我也尝试使用cURL在PHP中的请求,只是为了确保工作正常。 另外,在本地服务器(127.0.0.1)而不是远程服务器上执行完全相同的请求时,它也可以很好地工作。

Node.js的:

var postRequest = { host: "www.facepunch.com", path: "/newreply.php?do=postreply&t=" + threadid, port: 80, method: "POST", headers: { Cookie: "cookie", 'Content-Type': 'application/x-www-form-urlencoded' } }; buffer = ""; var req = http.request( postRequest, function( res ) { console.log( res ); res.on( "data", function( data ) { buffer = buffer + data; } ); res.on( "end", function() { require( "fs" ).writeFile( "output.html", buffer ); } ); } ); var body = "postdata\r\n"; postRequest.headers["Content-Length"] = body.length; req.write( body ); req.end(); 

cURL和PHP

 <?php if ( $_SERVER["REMOTE_ADDR"] == "127.0.0.1" ) { $body = "body"; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, "http://www.facepunch.com/newreply.php?do=postreply&t=" . $threadid ); curl_setopt( $ch, CURLOPT_POST, 15 ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $body ); curl_setopt( $ch, CURLOPT_COOKIE, "cookie" ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); $result = curl_exec( $ch ); curl_close( $ch ); } ?> 

这里发生了什么?

       

网上收集的解决方案 "node.js POST请求失败"

您将标头传递给http请求调用,然后尝试在事实之后添加Content-Length标头。 在传递值之前,你应该这样做,因为它改变了http请求设置的方式Transfer-Encoding

 var body = "postdata"; var postRequest = { host: "www.facepunch.com", path: "/newreply.php?do=postreply&t=" + threadid, port: 80, method: "POST", headers: { 'Cookie': "cookie", 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(body) } }; var buffer = ""; var req = http.request( postRequest, function( res ) { console.log( res ); res.on( "data", function( data ) { buffer = buffer + data; } ); res.on( "end", function() { require( "fs" ).writeFile( "output.html", buffer ); } ); } ); req.write( body ); req.end();