user61629 user61629 - 1 month ago 32
Javascript Question

How can I send POST data to a phantomjs script

I am working with PHP/CURL and would like to send POST data to my phantomjs script, by setting the postfields array below:

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFieldArray);
curl_setopt($ch, CURLOPT_URL, $url);
$output = curl_exec($ch);


The problem is I don't know how to parse a POST request inside the phantomjs script. I am using the webserver module to expose the script.

I suspect https://github.com/benfoxall/phantomjs-webserver-example/blob/master/server.js may have the answer, but I don't know enough javascript to tell whether post variables are being parsed:

var service = server.listen(port, function(request, response) {

if(request.method == 'POST' && request.post.url){
var url = request.post.url;

request_page(url, function(properties, imageuri){
response.statusCode = 200;
response.write(JSON.stringify(properties));
response.write("\n");
response.write(imageuri);
response.close();
})


Can someone show me how to parse a POST request here?

sjy sjy
Answer

The request.post object contains the body of the POST request. If your $postFieldArray is indeed an array, then (at least according to this answer) PHP should have encoded the array and POSTed it with the content type x-www-form-urlencoded. Actually, according to the PHP documentation:

Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

Although it is not explicit in the API reference, this GitHub issue suggests that PhantomJS will expose the content of an x-www-form-urlencoded form as properties on the request.post object. That's what seems to be happening in the example (request.post.url refers to the form field url). The easiest way to check would be to log the request.post object to the console and see what's in there.

However, the GitHub issue also implies that multipart/form-data is not supported by the PhantomJS webserver. So, unless you're prepared to change to a different web server, it might be easiest just to encode the data with JSON. On the PHP side:

curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postFieldArray)));

And then on the PhantomJS side:

var data = JSON.parse(request.post);
Comments