我试图将Node.js应用程序中的一些数据发布到PHP脚本.暂时我只是构建一个概念证明,但我无法将实际数据传递给PHP端.请求通过,我得到200回来,但PHP认为$ _POST数组是空的.
这是我的节点代码:
// simple end point just for testing exports.testPost = function(request, response) { data = request.body.data; postToPHP(data); response.end(data); } function postToPHP (data) { var http = require('http'); var options = { host : 'localhost', port : 8050, path : '/machines/test/index.php', method : 'POST', headers : { 'Content-Type' : 'application/json', 'Content-Length' : Buffer.byteLength(data) } }; var buffer = ""; var reqPost = http.request(options, function(res) { console.log("statusCode: ", res.statusCode); res.on('data', function(d) { console.info('POST Result:\n'); //process.stdout.write(d); buffer = buffer+data; console.info('\n\nPOST completed'); }); res.on('end', function() { console.log(buffer); }); }); console.log("before write: "+data); reqPost.write(data); reqPost.end(); }
同样,请求进入localhost:8050/machines/test/index.php,但当我执行$ _POST的var_dump时,它是一个空数组.
[29-Jan-2014 21:12:44] array(0) { }
我怀疑我在使用.write()方法做错了但是我无法弄清楚是什么.任何关于我遗失或做错的输入都将非常感激.
*更新:
有些评论表明使用了file_get_contents('php:// input'); 确实可以在PHP端获取数据,但我仍然希望能够直接访问$ _POST数组.
因为你正在发送数据,Content-Type: application/json
你需要读取原始输入,因为php不知道如何将json读入他们的全局变量,如_GET和_POST,除非你有一些php扩展来执行它.
您可以使用查询字符串库将对象解析为您可以传输的名称 - 值对查询字符串,Content-Type:application/x-www-form-urlencoded
以便将数据解析为全局变量
var data = { var1:"something", var2:"something else" }; var querystring = require("querystring"); var qs = querystring.stringify(data); var qslength = qs.length; var options = { hostname: "example.com", port: 80, path: "some.php", method: 'POST', headers:{ 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': qslength } }; var buffer = ""; var req = http.request(options, function(res) { res.on('data', function (chunk) { buffer+=chunk; }); res.on('end', function() { console.log(buffer); }); }); req.write(qs); req.end();