Postman的Collection(集合)/Folder(集合的子文件夾)/Request(請求)都有Pre-request script和Tests兩個腳本區域,分別可以在發送請求前和請求后使用腳本(基於Javascript實現各種操作)
集合的腳本區
文件夾的腳本區

請求的腳本區

在遇到有依賴的接口時,比如需要登錄或者需要從前一個接口的結果中獲取參數時,我們往往需要在該請求前先發送一下所依賴的請求, 我們可以在Pre-request script中使用pm.sendRequest實現
例1:Postman使用腳本發送get請求
const url = 'http://115.28.108.130:5000/api/user/getToken/?appid=136425'; // 發送get請求 pm.sendRequest(url, function (err, res) { console.log(err ? err : res.text()); // 控制台打印請求文本 });
可以配合pm.environment.set(key:value)來將響應中的數據保存到環境變量中以供本次請求使用
示例: 使用請求前腳本獲取token並使用,
例2:Postman使用腳本發送Post表單請求
//構造一個登錄請求 const loginRequest = { url: 'http://115.28.108.130:5000/api/user/login/', method: "POST", body: { mode: 'urlencoded', // 模式為表單url編碼模式 urlencoded: 'name=張三&password=123456' } }; // 發送請求 pm.sendRequest(loginRequest, function (err, res) { console.log(err ? err : res.text()); });
輸出信息可以通過點擊Postman菜單欄 ->view-> Show Postman Console, 打開控制台查看(先打開控制台,再發送請求)

例3:發送JSON格式請求(Postman腳本中發送JSON格式Post請求)
// 構造一個注冊請求 const regRequest = { url: 'http://115.28.108.130:5000/api/user/reg/', 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(err ? err : res.json()); // 響應為JSON格式可以使用res.json()獲取到JSON對象 });

例4:發送XML格式請求
發送XML格式和發送JSON格式差不多, 只要指定內容格式並發送相應的內容即可
//構造請求 const demoRequest = { url: 'http://httpbin.org/post', method: 'POST', header: 'Content-Type: application/xml', // 請求頭種指定內容格式 body: { mode: 'raw', raw: '<xml>hello</xml>' // 按文本格式發送xml } }; //發送請求 pm.sendRequest(demoRequest, function (err, res) { console.log(err ? err : res.json()); });
本文所演示接口- 接口文檔傳送門
個人實際開發環境中:
pm.sendRequest(pm.environment.get("token-url"), function (err, response) {
pm.environment.set("head-token", response.json().token)
});