邮递员发布预请求失败,原因是https

时间:2019-01-09 15:07:12

标签: postman postman-pre-request-script

我正在尝试设置一个邮递员预请求,以便在我对服务提出的每个请求之前获取OAuth令牌。

我尝试遵循与此相关的各种示例和指南,尽管由于请求前脚本失败,我的脚本仍然存在问题,但每个示例和指南似乎都很简单。

恐怕这与以下事实有关:我需要调用以获取令牌的端点位于http协议上,而不是https上,因为在Postman控制台中,我总是收到2个单独的请求到相同的url ,一个在https上,一个在http上。

这是我的请求前脚本

pm.expect(pm.environment.has('host')).to.be.true;
pm.expect(pm.environment.has('client_id')).to.be.true;
pm.expect(pm.environment.has('client_secret')).to.be.true;
pm.expect(pm.environment.has('username')).to.be.true;
pm.expect(pm.environment.has('password')).to.be.true;

var options = { method: 'POST',
  url: 'http://' + pm.environment.get("host") + '/api/oauth/token',
  headers: 
  { 
 Authorization: 'Basic '+btoa(pm.environment.get("client_id")+':'+pm.environment.get("client_secret")),
 'Content-Type': 'application/x-www-form-urlencoded' 

  },
  form: 
   { 
   grant_type: 'password',
   username: pm.environment.get('username'),
   password: pm.environment.get('password'),
   } 
};

pm.sendRequest(options, function(err, response) {
  console.log(response.json())
});

这就是我在Postman控制台中看到的内容

Postman douple post pre-request on different protocols

从图片中可以看到,第一个请求失败,第二个请求生成401 HTTP响应。

如果我在请求前脚本之外运行与HTTP上“常规”邮递员请求相同的请求,则一切正常,但在https上,由于甚至没有发出请求,我收到一个错误消息

如何使我的请求前脚本正常运行?

2 个答案:

答案 0 :(得分:0)

根据您的示例代码,我认为您输入了错误的“标题”。如果将其更改为“ header”,它应该可以工作。

答案 1 :(得分:0)

I finally figured out what the problem was.

There were multiple problems with the pre-script:

1) The double response was actually related to a double pre-script, one at the collection level and on at folder level inside the collection.

2) The request itself had to be changed because many parts were incorrect. As Mo a was saying the headers key was wrong and need to be header, but also the body is not correct as it require specific format.

Here you can find the new request working correctly

pm.expect(pm.environment.has('host')).to.be.true;
pm.expect(pm.environment.has('client_id')).to.be.true;
pm.expect(pm.environment.has('client_secret')).to.be.true;
pm.expect(pm.environment.has('username')).to.be.true;
pm.expect(pm.environment.has('password')).to.be.true;

var options = { 
  url: 'http://' + pm.environment.get("host") + '/api/oauth/token',
  method: 'POST',
  header: { 
Authorization: 'Basic '+btoa(pm.environment.get("client_id")+':'+pm.environment.get("client_secret")),
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
  },
  body: {
  mode: "urlencoded",
  urlencoded: [
      {key: "grant_type", value: "password", disabled: false},
      {key: "username", value: pm.environment.get('username'), disabled: false},
      {key: "password", value:  pm.environment.get('password'), disabled: false}
    ]
  }
};

pm.sendRequest(options, function(err, response) {
  pm.environment.set("oauth_token", response.json().access_token)
});

This pre-request works perfectly and stores the oauth_token in the proper variable