【问题标题】:node.js POST request failsnode.js POST 请求失败
【发布时间】:2011-09-07 11:29:31
【问题描述】:

我正在尝试使用 node.js 执行 POST 请求,但它似乎总是超时。我还尝试在 PHP 中使用 cURL 发出请求,以确保它工作正常。此外,当在我的本地服务器 (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 );
    }
?>

这是怎么回事?

【问题讨论】:

    标签: php post curl node.js request


    【解决方案1】:

    您将标头传递给 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 2013-03-21
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多