Node.js不发送适当的POST消息
我在node.js中有这样的代码:
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); ?>
很简单…但是在做了node.js POST请求之后 – PHP没有获得任何数据。 我已经尝试了很多其他的方式,使PHP的消息,但没有为我工作。 我的意思是, $_POST
总是空的。
试过还请求 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); }); });
我的问题应该有一个非常简单的解决scheme,但我找不到一个。
$_POST
数组只填充了HTML表单POST提交。 要模仿这样的表单提交,您需要:
- 将请求Content-Type标头完全设置为
application/x-www-form-urlencoded
- 在请求正文中使用表单编码…必要时,使用百分比编码的 IE
key=value&key2=value2
。 - 计算内容长度标题的值正好是正在发送的字节的长度。 只有完全编码的string后才能做到这一点,尽pipe为了计算内容长度,字节转换不是必须的,因为urlencodedstring中的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); ?>