These are chat archives for request/request

15th
Jun 2015
Mr-KoKa
@Mr-KoKa
Jun 15 2015 16:40
This message was deleted

I cannot figure out how to post json request. All I do is:

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);
        }
    }
});

I have test.php file:

<?php

    echo json_encode(
        array(
            'REQUEST' => $_REQUEST,
            'GET' => $_GET,
            'POST' => $_POST
        )
    );

and output from nodejs is:

> node test.js
{ REQUEST: [], GET: [], POST: [] }

When I change uri to eg. "http://127.0.0.1/test.php?test=abc" the output is:

> node test.js
{ REQUEST: { test: 'abc' }, GET: { test: 'abc' }, POST: [] }

So it is like none of body's value has been sent.

Mr-KoKa
@Mr-KoKa
Jun 15 2015 18:24
I figured out that when data is sent as json, php is not handling it usual way, so there is no data to be found in _POST or _REQUEST varaibles, but request body is need to be handled. I switched body option to form, and now it works just fine.