问题
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 screenshot

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.
回答1:
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();
}
});
来源:https://stackoverflow.com/questions/19550582/parsing-post-data-in-phantomjs