node.js sending ajax request using "request/request" package sends no data to server

283 views Asked by At

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?

1

There are 1 answers

0
Mr_KoKa On

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:

var options = {
    method: 'POST',
    uri: 'http://127.0.0.1/test.php',
    json: true,
    form: {
        data: JSON.stringify(value),
    }
};

Now we can read $_POST['data'] and use json_decode on it.