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
我的phantomjs脚本如下:
// 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();
}
});
当我在命令行运行 phantomjs 时,输出如下:
$ 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
所以,它似乎确实有效。我现在的问题是如何将帖子正文解析为变量,以便我可以在脚本的其余部分访问它。
要读取发布数据,您不应该使用request.headers
因为它是 HTTP 标头(编码、缓存、cookie...)
As said here http://phantomjs.org/api/webserver/,你应该使用request.post
or request.postRaw
.
request.post
是一个json对象,所以你将它写入控制台。这就是为什么你得到[object Object]
。尝试应用一个JSON.stringify(request.post)
记录时。
As request.post
是一个json对象,您也可以使用索引器直接读取属性(如果属性未发布,请不要忘记添加基本检查)
这是您的脚本的更新版本
// 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();
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)