postman高級用法之pre-request


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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM