Access to headers in request-promise get response

前端 未结 4 1281
陌清茗
陌清茗 2020-12-30 00:11

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 n

相关标签:
4条回答
  • 2020-12-30 00:19

    Just passing resolveWithFullResponse: true with in the get options should fetch the response headers.

    0 讨论(0)
  • 2020-12-30 00:28

    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.

    0 讨论(0)
  • 2020-12-30 00:29

    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...
    });
    
    0 讨论(0)
  • 2020-12-30 00:32

    Tsalikidis answer is correct. As for:

    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

    A promise (Promise/A+ compliant) always return one single value. Of course this value can be a deeply nested object with tons of information in it. But .then(function(response,body){ is inherently wrong.

    A library that sends back a promise should document the format of the returned object.

    0 讨论(0)
提交回复
热议问题