4

我正在使用 chrome 的 POSTMAN 扩展,并尝试向 phantomjs 发送发布请求 我已通过设置邮递员,如随附的屏幕截图所示,设法将发布请求发送到 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();

                }
 });  

当我在命令行运行 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

所以,它似乎确实有效。我现在的问题是如何将帖子正文解析为变量,以便我可以在脚本的其余部分中访问它。

4

1 回答 1

7

要读取发布数据,您不应使用request.headers它的 HTTP 标头(编码、缓存、cookie 等)

正如这里所说,您应该使用request.postor request.postRaw

request.post是一个 json 对象,所以你将它写入控制台。这就是为什么你得到[object Object]. 尝试JSON.stringify(request.post)在记录时应用。

由于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();
    }
});
于 2013-10-24T06:42:27.253 回答