Open kagxin opened 5 years ago
有时候,我们想在每次请求之前都获取一次token,Pre-request Script会在发生请求之前执行
先在variable中添加环境变量,这个环境变量在当前collection中有效
添加Pre-request Script
token 的格式根据实际进行修改
pm.sendRequest({ // pm.sendRequest 发一次http请求 url: "http://"+pm.variables.get('host')+"/api/v1/account/login/", //请求地址 method: 'POST', // 方法 header: { 'content-type': 'application/json', // 格式 'accept': 'application/json', }, body: { mode: 'raw', raw: JSON.stringify({login_name:pm.variables.get('username') , password: pm.variables.get('password')}) // body json 格式,username和password字段 } }, function (err, res) { // http回调函数 // pm.environment.set("token", "token " + res.json().data.access_token); //设置环境变量 pm.request.headers.add({ //设置header Authorization: token <?token> key: 'Authorization', value: "token " + res.json().data.access_token }); }); //
如何添加token
1、以编辑一个collection为例,设置header中的Authorization字段
2、如何在 Pre-request Script中添加请求获取token
先在variable中添加环境变量,这个环境变量在当前collection中有效
添加Pre-request Script