2013-02-03 77 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); 
?>