我正在尝试将一些数据从 Node.js 应用程序发布到 PHP 脚本。目前我只是在构建一个概念证明,但我无法将实际数据传递到 PHP 端。请求通过,我得到了 200,但 PHP 认为 $_POST 数组是空的。
这是我的 Node 代码:
// 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 扩展可以做到这一点。
您可以使用 querystring库将对象解析为名称-值对查询字符串,您可以使用 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();
关于javascript - 从 Node.js POST 到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21441786/