本文介绍了访问请求承诺中的标头以获取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS世界的新手.我正在尝试编写一个测试用例,以测试用户在站点上的操作.我正在使用request-promise模块来测试asyn调用.我找不到用于请求承诺的任何api文档.如何获得响应的状态码?现在,它打印未定义.另外,任何人都可以确认一下,我们如何知道诺言成功后会返回什么,它是解析为的单个值还是异步函数返回的所有参数.

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

推荐答案

默认情况下,请求承诺库仅返回响应本身.但是,您可以在选项中传递一个简单的转换函数,该函数具有三个参数,并允许您返回其他内容.

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

希望有帮助.

这篇关于访问请求承诺中的标头以获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 09:55