Node.js not sending proper POST message
Problem
I've got such a code in 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();
and PHP code:
quite simple... but after making node.js POST request - PHP is not obtaining any data. I've tried many other ways of making that POST message to PHP but nothing works for me. I mean, $_POST
is always empty.
Tried also request Nodejs library:
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);
});
});
There should be really simple solution for my problem but I can't find one.
Problem courtesy of: Wojciech Dłubacz
Solution
The $_POST
array is only populated with HTML form POST submits. To emulate such a form submit, you need to:
- Set the request Content-Type header exactly to
application/x-www-form-urlencoded
- Use the form encoding in the request body... I.E
key=value&key2=value2
with percent-encoding where necessary. - Calculate the Content-Length header's value exactly to the length of bytes that are being sent. You can only do this after having the fully encoded string, though byte conversion is not necessary in order to calculate the Content-Length since 1 character = 1 byte in urlencoded string.
However, with your current code (provided all you have is ASCII), you can also do this:
Solution courtesy of: Esailija
Discussion
View additional discussion.