postman高级用法之pre-request
1.简单用法
//获取、设置、删除环境变量 pm.environment.get("variable_key"); pm.environment.set("variable_key", "variable_value"); pm.environment.unset("variable_key"); //获取设定删除全局变量 pm.globals.get("variable_key"); pm.globals.set("variable_key", "variable_value"); pm.globals.unset("variable_key"); //获取普通变量 pm.variables.get("variable_key"); //获取设置、删除集合变量 pm.collectionVariables.get("variable_key"); pm.collectionVariables.set("variable_key", "variable_value"); pm.collectionVariables.unset("variable_key"); //发送一个get请求 pm.sendRequest("https://postman-echo.com/get", function (err, response) { console.log(response.json()); });
2.发送前置post请求,从中获取cookie,然后应用到第二个请求的header,常用于鉴权
const loginRequest={ url:"https://www.xxx.com/api/user/login", method:"POST", header: [ "Content-Type: application/x-www-form-urlencoded; charset=UTF-8", "appVer: 4.4.0", ], body: { mode: 'raw', raw: 'loginName=user&loginPwd=pswd' } }; pm.sendRequest(loginRequest,function(err,response){ r = JSON.parse(JSON.stringify(response)); for(var x of r.header){ if(x.key=="Set-Cookie"){ console.log(x.value); pm.collectionVariables.set("cookie",x.value); } } });