Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to headers in request-promise get response

Tags:

I am complete newbie to JS world. I am trying to write a test case that tests user's actions on a site. I am using request-promise module to test the asyn calls. I could not find any api documentation for request-promise. How do I get access to status code of the response? Right now it prints undefined. Also, can anyone please confirm, how do we know what promise returns when it is successful, is it a single value that it resolves to or all the parameters that the async function returns. How do we know what are the parameters to function() in request.get(base_url).then(function(response, body).

var request = require("request-promise"); var promise = require("bluebird"); // var base_url = "https://mysignin.com/" // describe("My first test", function() {  it("User is on the sign in page", function(done) {     request.get(base_url).then(function(response, body){      // expect(response.statusCode).toBe('GET /200');       console.log("respnse " + response.statusCode);       console.log("Body " + body);       done();     }).catch(function(error) {         done("Oops somthing went wrong!!");     });  }); }); 
like image 543
learningtocode Avatar asked Aug 30 '16 18:08

learningtocode


People also ask

How do I get response header responses?

View headers with browser development toolsSelect the Network tab. You may need to refresh to view all of the requests made for the page. Select a request to view the corresponding response headers.


2 Answers

By default, the request-promise library returns only the response itself. You can, however, pass a simple transform function in your options, which takes three parameters and allows you to return additional stuff.

So if I wanted the headers plus the response returned to me, I would just do this:

var request = require('request-promise'); var uri = 'http://domain.name/';  var _include_headers = function(body, response, resolveWithFullResponse) {   return {'headers': response.headers, 'data': body}; };  var options = {   method: 'GET',   uri: uri,   json: true,   transform: _include_headers, }  return request(options) .then(function(response) {   console.log(response.headers);   console.log(response.data); }); 

Hope that helps.

like image 94
Rob Bailey Avatar answered Oct 02 '22 09:10

Rob Bailey


By default request-promise returns just the response body from a request. To get the full response object, you can set resolveWithFulLResponse: true in the options object when making the request. Example in the docs

var request = require('request-promise');  request.get('someUrl').then(function(body) {   // body is html or json or whatever the server responds });  request({   uri: 'someUrl',   method: 'GET',   resolveWithFullResponse: true }).then(function(response) {   // now you got the full response with codes etc... }); 
like image 30
Kostas Avatar answered Oct 02 '22 10:10

Kostas