【问题标题】:Access to headers in request-promise get response访问 request-promise 中的 headers 得到响应
【发布时间】:2019-07-09 13:30:48
【问题描述】:

我是 JS 世界的新手。我正在尝试编写一个测试用户在网站上的操作的测试用例。我正在使用 request-promise 模块来测试异步调用。我找不到任何请求承诺的 api 文档。 如何访问响应的状态代码?现在它打印未定义。另外,任何人都可以确认一下,我们如何知道 Promise 成功时返回的内容,是它解析为的单个值还是异步函数返回的所有参数。我们如何知道request.get(base_url).then(function(response, body) 中 function() 的参数是什么。

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!!");
    });
 });
});

【问题讨论】:

标签: javascript promise


【解决方案1】:

默认情况下,request-promise 库只返回响应本身。但是,您可以在选项中传递一个简单的转换函数,该函数接受三个参数并允许您返回其他内容。

所以如果我想要标头和返回给我的响应,我会这样做:

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

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    默认情况下,request-promise 仅返回请求的响应正文。要获取完整的响应对象,您可以在发出请求时在选项对象中设置resolveWithFulLResponse: trueExample 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...
    });
    

    【讨论】:

      【解决方案3】:

      只需在 get 选项中传递 resolveWithFullResponse: true 即可获取响应标头。

      【讨论】:

        【解决方案4】:

        Tsalikidis 的答案是正确的。 至于:

        另外,谁能确认一下,我们怎么知道承诺返回什么? 当它成功时,它是解析为单个值还是全部 async 函数返回的参数

        promise(符合 Promise/A+)总是返回一个值。当然,这个值可以是一个深度嵌套的对象,其中包含大量信息。但是.then(function(response,body){ 本身就是错误的。

        发回承诺的库应该记录返回对象的格式。

        【讨论】:

          猜你喜欢
          • 2022-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-16
          • 2018-12-29
          • 2017-07-26
          • 1970-01-01
          相关资源
          最近更新 更多