2

I've tried all the examples on these SO posts:

How do I send a POST request with PHP?

PHP cURL Post request not working

Always my request.body is undefined yet in the request itself I see "_hasBody":true

The current code for my php post file:

function httpPost($url,$data){
    $curl = curl_init($url);
    curl_setopt($curl,CURLOPT_POST,true);
    curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($data));
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    $response=curl_exec($curl);
    curl_close($curl);
    return $response;
    }
$fields = array(
    'name' => 'ben'
,   'foo'  => 'bar'
    );
echo httpPost("http://localhost:8002", $fields);

Then my node.js listening server code is:

var test=require('http').createServer(function(q,a){//question,answer
    console.log(q.body);
    console.log(JSON.stringify(q).indexOf('ben'));
    a.end(JSON.stringify(q));
    });
test.listen(8002,function(e,r){console.log("listening");});

As you can see, in the node.js server I search the request for my name but the console says

undefined//no body
-1//could not find your name in the request

then I hand over the request back to the response and print it to the page so I can see the whole data.

logically it would seem that I am doing the cURL part right as its copied code, so I would say I might be doing something wrong to access the vars

My question is how do I see the request body or where the vars?

Community
  • 1
  • 1
Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66

1 Answers1

5

To handle a POST request, you have to do the following:

var qs = require('querystring');
var http = require('http');

var test = http.createServer(function(req, res) { 

    //Handle POST Request
    if (req.method == 'POST') {
        var body = '';
        req.on('data', function(data) {
            body += data;           
        });

        req.on('end', function() {
            var POST = qs.parse(body);

            console.log(body); // 'name=ben&foo=bar'
            console.log(POST); // { name: 'ben', foo: 'bar' }

            if(POST.name == 'ben')
               console.log("I'm ben"); //Do whatever you want.

            res.setHeader("Content-Type", "application/json;charset=utf-8");
            res.statusCode = 200;
            res.end(JSON.stringify(POST)); //your response
        });
    }

});

test.listen(8002, function(e, r) {
    console.log("listening");
});

cURL response:

{"name":"ben","foo":"bar"}
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98