Consume web services in PhantomJS - part 2

Usage

In the following sample we send a GET request without parameters:

samle_01.js - GET request
 var page  = require('webpage').create();
 var phreq = require("./phrequest");
 var rq = new phreq.PhRequest();

 rq.url = 'https://jsonplaceholder.typicode.com/posts/1';

 phreq.request(page, rq, function (text, code) {
     console.log('The code is ==> ' + code);
     console.log(text);
     phantom.exit(0);
 });
sample_01.js - Output
 The code is ==> 200
 {
   "userId": 1,
   "id": 1,
   "title": "...",
   "body": "..."
 }

In the following sample, we send a GET request with parameters. The rq.urlQuery will be set to the actual endpoint URL.

sample_02.js - GET request with Query Parameters
 var page  = require('webpage').create();
 var phreq = require("./phrequest");
 var rq = new phreq.PhRequest();

 var rq = new phreq.PhRequest;
 rq.url = 'https://jsonplaceholder.typicode.com/posts'
 rq.qs.userId = 2;

 phreq.request(page, rq, function (text, code) {
     console.log('The URL is  ==> ' + rq.urlQuery);
     console.log('The code is ==> ' + code);
     console.log(text);
     phantom.exit(0);
 });
sample_02.js - output
 The URL is  ==> https://jsonplaceholder.typicode.com/posts?userId=2
 The code is ==> 200
 [
   {
     "userId": 2,
     "id": 11,
     "title": "...",
     "body": "..."
   },
   ...
 ]

In the following sample we send a POST request with JSON as body. The addJson body takes an object as parameter. This object is converted to JSON and assigned the PhRequest.data. The method also set the Content-Type header to application/json.

sample_03.js - POST request with JSON body
 var page  = require('webpage').create();
 var phreq = require("./phrequest");
 var rq = new phreq.PhRequest();

 var rq = new phreq.PhRequest;
 rq.url    = 'https://jsonplaceholder.typicode.com/posts'
 rq.method = 'POST';
 rq.addJson( {title: 'foo bar',body: 'bar',userId: 2} )

 phreq.request(page, rq, function (text, code) {
     console.log('The code is ==> ' + code);
     console.log(text);
     phantom.exit(0);
 });
sample_03.js - output
 The code is ==> 201
 {
   "title": "foo bar",
   "body": "bar",
   "userId": 2,
   "id": 101
 }