use*_*629 4 javascript phantomjs
我正在使用POSTMAN扩展到chrome并且我正在尝试向phantomjs发送一个帖子请求我已设法通过设置postman发送一个post请求到一个phantomjs服务器脚本,如附带的屏幕截图
我的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();
}
});
Run Code Online (Sandbox Code Playgroud)
当我在命令行运行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
Run Code Online (Sandbox Code Playgroud)
所以,它似乎确实有效.我现在的问题是如何将post body解析为变量,所以我可以在脚本的其余部分访问它.
要阅读发布数据,您不应该使用request.headers它的HTTP标头(编码,缓存,cookie,...)
至于说在这里,你应该使用request.post或request.postRaw.
request.post是一个json对象,所以你把它写入控制台.这就是你得到的原因[object Object].尝试JSON.stringify(request.post)在登录时应用.
作为request.postjson对象,您也可以使用索引器直接读取属性(如果未发布属性,请不要忘记添加基本检查)
这是您脚本的更新版本
// 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();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3893 次 |
| 最近记录: |