I am trying to POST some data from a Node.js application to a PHP script. For the time being I am just building a proof of concept but I am unable to get the actual data ov
Since you are sending the data with Content-Type: application/json
you would need to read the raw input as php does not know how to read json into their globals like _GET and _POST unless you have some php extension that does it.
You can use the querystring library to parse a object into a name-value pair query string that you could than transmit with Content-Type:application/x-www-form-urlencoded
so that the data will be parsed into the globals
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();