Postman 使用教程(三)

postman定义环境变量和全局变量用的比较多,当使用多个集合(collection) 的时候,每个集合也可以分别定义不同的集合变量。
一个集合可以看成一个小的项目,不同集合定义不同变量是很有必要的。

定义集合变量

 

使用集合变量

postman 可以在接口请求Pre-request 添加请求前的操作,很多接口都是依赖于先登录的。于是可以在Pre-request 发送一个登录请求获取token。
当接口较多的时候,每个接口前面加一次会很麻烦,这种公共操作可以写到collection 集合中添加 Pre-request Scripts

postman -collection 添加Pre-request Scripts 解决登录依赖问题

collection添加Pre-request Scripts

const regRequest = {
  url: 'https://XXX/authority/login',
  method: 'POST',
  header: 'Content-Type: application/json',  
  body: JSON.stringify({userKey:"测试",passWord:"13",currentUserId:"",operator:""})
};

// 发送登录请求,获取响应头中的token  获取响应body 中的userId
pm.sendRequest(regRequest, function (err, res) {
  headers_list = res.headers
  pm.variables.set('userId', res.json()['data']['userId'])
  pm.variables.set('token', headers_list.get("H-AUTH-TOKEN"))

});

// 将获取到的token 添加到 请求头部
pm.request.headers.add({
    key:"Authorization",
    value:"{{token}}"
});

依赖登录的接口

依赖登录的接口,请求头部不需要再添加Authorization:{{token}}

 查看Console 可以看到会先执行登录,自动更新请求头部token值

posted @ 2022-01-11 16:07  keena_jiao  阅读(119)  评论(0编辑  收藏  举报