4

I am trying to send a post request through PHP cURL to my node.js server to then emit a message to the client. The server is working and setup as follows:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , qs = require('querystring')

app.listen(8000);

function handler(req, res) {
    // set up some routes
    switch(req.url) {
        case '/push':

        if (req.method == 'POST') {
            console.log("[200] " + req.method + " to " + req.url);
            var fullBody = '';

            req.on('data', function(chunk) {
                fullBody += chunk.toString();

                if (fullBody.length > 1e6) {
                    // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                    req.connection.destroy();
                }
            });

            req.on('end', function() {              
                // Send the notification!
                var json = qs.stringify(fullBody);
                console.log(json.message);

                io.sockets.emit('push', { message: json.message });

                // empty 200 OK response for now
                res.writeHead(200, "OK", {'Content-Type': 'text/html'});
                res.end();
            });    
        }

        break;

        default:
        // Null
  };
}

and my PHP is as follows:

    $curl = curl_init();
    $data = array('message' => 'simple message!');

    curl_setopt($curl, CURLOPT_URL, "http://localhost:8000/push");
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_exec($curl);

The console says that json.message is undefined. Why is it undefined?

2
  • Why don't you add a console.log(fullBody) to see what you are processing? I suspect the error is that the body is not what you expect. Commented Sep 7, 2012 at 0:32
  • Thanks mate! Just solved the problem. The fullBody var is now working as intended, and so json should actually = qs.parse(fullBody), not qs.stringify(fullBody). Commented Sep 7, 2012 at 0:40

4 Answers 4

2

You're using querystring.stringify() incorrectly. See the documentation on querystring's methods here:

http://nodejs.org/docs/v0.4.12/api/querystring.html

I believe what you want is something like JSON.stringify() or querystring.parse(), as opposed to querystring.stringify() which is supposed to serialize an existing object into a query string; which is the opposite of what you are trying to do.

What you want is something that will convert your fullBody string into a JSON object.

Sign up to request clarification or add additional context in comments.

Comments

2

If your body simply contains a stringified version of the JSON blob, then replace

var json = qs.stringify(fullBody);

With

var json = JSON.parse(fullBody);

Comments

0

try this code

<?php

$data = array(
    'username' => 'tecadmin',
    'password' => '012345678'
);
 
$payload = json_encode($data);
 
// Prepare new cURL resource
$ch = curl_init('https://api.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 
// Set HTTP Header for POST request 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);
 
// Submit the POST request
$result = curl_exec($ch);
 
// Close cURL session handle
curl_close($ch);

Comments

0

For me it was

$data = array(
    'name' => 'John Doe',
    'email' => '[email protected]',
    'phone' => '1234567890'
);

$json = json_encode($data);
$data = array('simple message!');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json)
));
$result = curl_exec($ch);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.