本文為博主原創,轉載請注明出處:
Pre-request Script 為Postman預置腳本,用於在postman 發送請求之前執行,封裝計算或獲取某些請求參數。
1. postman 腳本提供了一些默認封裝好的對象和屬性。
整個請求對象為 postman 或 pm 。
通過postman 或 pm 可以設置一些環境變量參數,可以動態獲取。
pm.environment.set(key,value); 設置環境變量
pm.globals.unset("variable_key"); 清除全局變量 pm.environment.unset("variable_key"); 清除環境變量 pm.globals.get("variable_key"); 獲取全局變量 pm.variables.get("variable_key"); 獲取一個變量 pm.environment.get("variable_key"); 獲取環境變量 pm.sendRequest("https://postman-echo.com/get", function (err, response) { console.log(response.json()); }); 發送一個請求 pm.globals.set("variable_key", "variable_value"); 設置環境變量
2. 通過 pre-request script 設置環境變量,並進行接口請求
其中也可以添加console 打印調試日志。可以查看計算出來的參數值。
var timestamp = Math.round(new Date().getTime()/1000); console.log("timestamp is "+ timestamp); pm.environment.set("timestamp",timestamp); // 構造一個注冊請求 const regRequest = { url: 'localhost:8002/user/getNonce', method: 'POST', header: 'Content-Type: application/json', //注意要在Header中聲明內容使用的類型 body: { mode: 'raw', // 使用raw(原始)格式 raw: JSON.stringify({ name: '小小', password: '123456' }) //要將JSON對象轉為文本發送 } }; //發送請求 pm.sendRequest(regRequest, function (err, res) { console.log("res == "+res); // 響應為JSON格式可以使用res.json()獲取到JSON對象 console.info(res); pm.environment.set("nonce", res.json().value) });
上面腳本定義了一個 timestamp 的變量,並設置到環境變量中, 並將 請求 /user/getNonce 返回的值定義為nonce值,存儲到環境變量中。
如何使用預置腳本中的變量,通過 {{ }} 既可。調用如下:
示例中 pm.sendRequest 發送請求的格式為post 請求,請求體為json 格式。如果是 post form 請求時,更改 regRequest 中德mode 既可:
const regRequest = { url: 'localhost:8002/user/getNonce', method: 'POST', header: 'Content-Type: application/json', //注意要在Header中聲明內容使用的類型 body: { mode: ‘urlencoded’, urlencoded: [{ “key”: “grant_type”, “value”: “client_credentials”, }] } };
//發送請求
pm.sendRequest(regRequest, function (err, res) {
console.log("res == "+res); // 響應為JSON格式可以使用res.json()獲取到JSON對象
console.info(res); pm.environment.set("nonce", res.json().value) });
如果是get 請求:
const url = 'http://localhost:5000/api/user/getToken/?appid=136425'; // 發送get請求 pm.sendRequest(url, function (err, res) { console.log(err ? err : res.text()); // 控制台打印請求文本 });