4

POSTMAN 拡張機能を chrome で使用していて、phantomjs に投稿要求を送信しようとしています。添付の​​スクリーンショットのように postman を設定することで、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.headersHTTP ヘッダー (エンコード、キャッシュ、Cookie など) をそのまま使用しないでください。

ここで述べたように、request.postまたはを使用する必要がありますrequest.postRaw

request.postjson オブジェクトなので、コンソールに書き込みます。それがあなたが得る理由です[object Object]JSON.stringify(request.post)ロギング時にa を適用してみてください。

json オブジェクトと同様request.postに、インデクサーを使用してプロパティを直接読み取ることもできます (プロパティが投稿されていない場合は、基本的なチェックを追加することを忘れないでください)。

ここにあなたのスクリプトの更新版があります

// 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 に答える