2013-02-03 81 views
1

我有這樣的代碼在node.js中:Node.js的不正確發送POST消息

var requestData = JSON.stringify({ id : data['user_id'] }); 
var options = { 
    hostname: 'localhost', 
    port: 80, 
    path: '/mypath/index.php', 
    method: 'POST', 
    headers: { 
     "Content-Type": "application/json", 
     'Content-Length': requestData.length 
    } 
}; 

var req = http.request(options, function(res) { 
    console.log('STATUS: ' + res.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res.headers)); 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     console.log('BODY: ' + chunk); 
    }); 
}); 

req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

// write data to request body 
req.write(requestData); 
req.end(); 

和PHP代碼:

<?php 
    $data = $_POST; 
    define('DS', '/'); 
    umask(000); 
    file_put_contents(dirname(__FILE__).DS.'log.txt', json_encode($data), FILE_APPEND); 
    echo json_encode($data); 
?> 

很簡單......但使節點之後.js POST請求 - PHP沒有獲取任何數據。我已經嘗試了許多其他的方法來將這條POST消息發送給PHP,但對我來說沒有任何作用。我的意思是,$_POST總是空。

也試過request庫的NodeJS:

request.post({ 
     uri : config.server.protocol + '://localhost/someurl/index.php', 
     json : JSON.stringify({ id : data['user_id'] }), 
     }, 
     function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
      console.log('returned BODY:', body); 
     } 
     def.resolve(function() { 
      callback(error); 
     }); 
    }); 

應該有我的問題非常簡單的解決方案,但我不能找到一個。

回答

3

$_POST數組僅填充HTML表單POST提交。爲了模擬這種形式提交,您需要:

  • 將請求Content-Type頭正好到application/x-www-form-urlencoded
  • 使用在請求體的形式編碼......即key=value&key2=value2percent-encoding必要。
  • 計算內容長度標頭的值,正好是發送的字節的長度。只有完全編碼的字符串後才能執行此操作,儘管字節轉換對於計算內容長度不是必需的,因爲urlencoded字符串中的1個字符= 1個字節。

然而,當前的代碼(前提是你必須是ASCII),你也可以這樣做:

<?php 
    $data = json_decode(file_get_contents("php://input")); 
    $error = json_last_error(); 
    if($error !== JSON_ERROR_NONE) { 
     die("Malformed JSON: " . $error); 
    } 

    define('DS', '/'); 
    umask(000); 
    file_put_contents(dirname(__FILE__).DS.'log.txt', json_encode($data), FILE_APPEND); 
    echo json_encode($data); 
?>