How to get a response after a POST request in CasperJS

I have this very simple code to read the response from the server endpoint after the mail request. In fact, I save the data in the database and wait for a response before moving on to the next step.

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

in ajax.php file I am trying to perform a POST ping in a simple way. this will make it easy for me to know if I get the correct answer from the server.

echo json_encode($_POST);

I tried these snippets, but I can not get the answer.

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
source share
3 answers

I ran into the same issue of POSTing a request to ElasticSearch, and I could not get the results.

As far as I can understand if you want to get the data selected by your script, the solution could be as follows:

this.echo(this.page.content);

or

this.echo(this.page.plainText);

in your function.

( 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();
+3

. this.page.content, . () script. :

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);
    }
});
+1

If you want a unit test REST API, CasperJS is not necessarily the right tool. CasperJS allows you to observe the web browser on which the web page is running. So a more typical approach is to use CasperJS to load a page that will call your REST API, and you claim that the page behavior is correct (it is assumed that the page will do something observable in accordance with the response to the AJAX call).

-4
source

All Articles