Postman的Collection(集合)/Folder(集合的子文件夾)/Request(請求)都有Pre-request script和Tests兩個腳本區域, 分別可以在發送請求前和請求後使用腳本(基於Javascript實現各種操作)
集合的腳本區
文件夾的腳本區
請求的腳本區
在遇到有依賴的接口時,比如需要登錄或者需要從前一個接口的結果中獲取參數時,我們往往需要在該請求前先發送一下所依賴的請求, 我們可以在Pre-request script中使用pm.sendRequest實現
- 發送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並使用,
Postman使用腳本發送get請求
- 發送表單格式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, 打開控制檯查看(先打開控制檯,再發送請求)
Postman使用腳本發送Post表單請求
- 發送JSON格式請求
// 構造一個註冊請求
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對象
});
Postman腳本中發送JSON格式Post請求
- 發送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());
});