I'm trying to send some data to php script from node.js script using https://github.com/request/request library but it seems like lib is sending no data.
My test.js:
var request = require('request');
var value = {
trueProperty: true,
falseProperty: false,
numberProperty: -98346.34698,
stringProperty: 'string',
nullProperty: null,
arrayProperty: ['array'],
objectProperty: { object: 'property' }
};
var options = {
method: 'POST',
uri: 'http://127.0.0.1/test.php',
json: true,
body: value,
};
request(options, function (error, response, json) {
if (!error && response.statusCode == 200) {
console.log(json);
} else {
console.log('Error has occurred:');
if(error){
console.log(error)
}
if(response){
console.log("Response status code: " + response.statusCode);
}
}
});
My test.php script:
<?php
echo json_encode(
array(
'REQUEST' => $_REQUEST,
'GET' => $_GET,
'POST' => $_POST
)
);
When I run test.js script the result is:
> node test.js
{ REQUEST: [], GET: [], POST: [] }
Any idea what can be wrong?
Update I modified test.php to return request body:
echo json_encode(
array(
'REQUEST' => $_REQUEST,
'GET' => $_GET,
'POST' => $_POST,
'BODY' => print_r(file_get_contents('php://input'), true)
)
);
now node's output looks like:
{ REQUEST: [],
GET: [],
POST: [],
BODY: '{"trueProperty":true,"falseProperty":false,"numberProperty":-98346.34698,"stringProperty":"string","nullProperty":null,"arrayProperty":["array"],"objectProperty":{"object":"property"}}' }
So it just PHP is not handling data, are they sent incorrectly or something?
Modifying options set by changing body key to form key makes php place variables in $_POST & $_REQUEST arrays, json: true stays as it is, it makes response to our request will be automatically JSON.parse-d.
Updated options looks like:
Now we can read $_POST['data'] and use json_decode on it.