2011-06-02 214 views
2

我試圖用node.js執行POST請求,但它似乎總是超時。我也嘗試使用PHP中的cURL來完成請求,以確保工作正常。另外,在我的本地服務器(127.0.0.1)而不是遠程服務器上執行完全相同的請求時,它也可以很好地工作。node.js POST請求失敗

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

捲曲和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); 
    } 
?> 

這到底是怎麼回事?

回答

3

您正在將標頭傳遞給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();