Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing post data in phantomjs

I am working with the POSTMAN extension to chrome and am trying to send a post request to phantomjs I have managed to send a post request to a phantomjs server script by setting postman as in the attached screenshotenter image description here

My phantomjs script is as follows:

// import the webserver module, and create a server
var server = require('webserver').create();
var port = require('system').env.PORT || 7788;     

console.log("Start Application");
console.log("Listen port " + port);    

// Create serever and listen port 
server.listen(port, function(request, response) {    

      console.log("request method: ", request.method);  // request.method POST or GET     

      if(request.method == 'POST' ){
                       console.log("POST params should be next: ");
                       console.log(request.headers);
                    code = response.statusCode = 200;
                    response.write(code);
                    response.close();

                }
 });  

when I run phantomjs at the command line , here is the output:

$ phantomjs.exe myscript.js
Start Application
Listen port 7788
null
request method:  POST
POST params should be next:
[object Object]
POST params:  1=bill&2=dave

So , it does appear to work. My question is now how to parse post body into variables, so I can access it in the rest of the script.

like image 430
user1592380 Avatar asked Mar 21 '23 22:03

user1592380


1 Answers

To read post data, you should not use request.headers as it's HTTP headers (encoding, cache, cookies, ...)

As said here, you should use request.post or request.postRaw.

request.post is a json object, so you write it into the console. That's why you get [object Object]. Try to apply a JSON.stringify(request.post) when logging.

As request.post is a json object, you can also directly read properties using indexers (do not forget to add a basic check if the property is not posted)

Here is an updated version of your script

// import the webserver module, and create a server
var server = require('webserver').create();
var port = require('system').env.PORT || 7788;

console.log("Start Application");
console.log("Listen port " + port);

// Create serever and listen port 
server.listen(port, function (request, response) {

    console.log("request method: ", request.method);  // request.method POST or GET     

    if (request.method == 'POST') {
        console.log("POST params should be next: ");
        console.log(JSON.stringify(request.post));//dump
        console.log(request.post['1']);//key is '1'
        console.log(request.post['2']);//key is '2'
        code = response.statusCode = 200;
        response.write(code);
        response.close();
    }
});
like image 76
Cybermaxs Avatar answered Apr 01 '23 19:04

Cybermaxs