Wojciech Dłubacz
Wojciech Dłubacz

Reputation: 219

Node.js not sending proper POST message

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:

<?php
    $data = $_POST;
    define('DS', '/');
    umask(000);
    file_put_contents(dirname( __FILE__ ).DS.'log.txt', json_encode($data), FILE_APPEND);
    echo json_encode($data);
?>

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.

Upvotes: 1

Views: 730

Answers (1)

Esailija
Esailija

Reputation: 140236

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:

<?php
    $data = json_decode(file_get_contents("php://input"));
    $error = json_last_error();
    if( $error !== JSON_ERROR_NONE ) {
        die( "Malformed JSON: " . $error );
    }

    define('DS', '/');
    umask(000);
    file_put_contents(dirname( __FILE__ ).DS.'log.txt', json_encode($data), FILE_APPEND);
    echo json_encode($data);
?>

Upvotes: 3

Related Questions