如何在CasperJS中的POST请求后获取响应

时间:2014-02-11 15:13:11

标签: phantomjs casperjs

我有这个非常简单的代码来在发布请求后从服务器端点读取响应。实际上我正在将数据保存到数据库并在进入下一步之前等待响应

casper.open('http://example.com/ajax.php, {
    method: 'POST',
    data: {
        'title': '<title>',
        'unique_id': '<unique_id>'
    }
});

在ajax.php文件上我试图以一种简单的方式回应POST请求。 如果我从服务器得到正确的答案,这将让我很容易知道。

echo json_encode($_POST);

我试过这些片段,但我无法得到答案。

casper.on('page.resource.received', function(resp){
    this.echo(JSON.stringify(resp, null, 4));
});

casper.on('http.status.200', function(resp){
    this.echo(JSON.stringify(resp, null, 4));
});

casper.on('resource.received', function(resp) {
    this.echo(JSON.stringify(resp, null, 4));
});

3 个答案:

答案 0 :(得分:3)

我一直面临同样的问题,将查询发布到ElasticSearch,我无法检索结果。

据我所知,如果您想要检索脚本回显的数据,解决方案可能是:

this.echo(this.page.content);

this.echo(this.page.plainText);

在你的功能中。

例如(我使用ElasticSearch的情况):

/*
 * SOME VAR DEFINITIONS HERE    
 */

casper.start();

casper.then( function() {
    // the next var is very specific to ElasticSearch
    var elasticQuery = JSON.stringify (
      {
        'size' : 20,
        'query' : {
          'filtered' : {
            'filter' : { 'term' : { 'locked' : false } }
          }
        },
        'sort': { 'lastScrapeTime': { 'order': 'asc' } }
      }
    );

    var elasticRequest = {
      method: 'POST',
      data: elasticQuery
    }

    this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
      // dump response header
      require('utils').dump(response);

      // echo response body
      this.echo(this.page.content);

      // echo response body with no tags added (useful for JSON)
      this.echo(this.page.plainText);
    }); 
  }
);

casper.run();

答案 1 :(得分:1)

罗伯托指出。您可以使用this.page.content来显示响应。但是您需要在脚本中添加函数(响应)。例如:

casper.open('http://example.com/ajax.php', {
    method: 'POST',
    data: {
        'title': '<title>',
        'unique_id': '<unique_id>'
    }
}, function(response){
    if(response.status == 200){
        require('utils').dump(this.page.content);
    }
});

答案 2 :(得分:-4)

如果要对REST API进行单元测试,CasperJS不一定是正确的工具。 CasperJS允许观察运行网页的Web浏览器。 因此,更典型的方法是使用CasperJS加载一个可以调用REST API的页面,并断言页面行为是正确的(假设页面会根据AJAX调用响应生成一些可观察的内容)。

相关问题