开发者

node.js POST request fails

I'm trying to perform a POST request with node.js, but it always seems to time out. I also tried doing the request with cURL in PHP just to make sure and that works fine. Also, when performing the exact same request on my local server (127.0.0.1) instead of the remote server, it works perfectly fine too.

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

What is going on here?


You're passing the headers to the http request call and then trying to add the Content-Length header after the fact. You should be doing that before you pass in the values, as it changes the way http request sets up 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜