在执行一些请求时,需要先执行其他请求做为预先条件,例如请求登陆接口时,先请求获取验证码的接口,等等
官网说明:https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#sending-requests-from-scripts
以下是几个例子:
1. 发送get请求
const regRequest = {
url : 'https://www.abc.com/a1aa/auth/dja?_t=1614319579',
method : 'GET'
};
// 获取验证码
pm.sendRequest(regRequest, function (err, response) {
pm.globals.set("global_yanzhengma", response.json().result.verifyCode);
pm.globals.set("global_yanzhengma_id", response.json().result.verifyId);
console.log(response.json());
});
2. 发送json格式的post请求
data = {
loginId: "zhangsan",
password: "111111"
};
// 登陆
const regRequest = {
url : 'https://www.abc.com/aaa/1/auth/signIn',
method : 'POST',
header : {
'Content-Type' : 'application/json;charset=UTF-8'
},
body : {
mode : 'raw',
raw : JSON.stringify(data)
}
};
pm.sendRequest(regRequest, function (err, response) {
console.log(response.json());
});
stringify将js对象转换为json
3. 发送x-www-form-urlencoded格式的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());
});
4. 发送一个xml格式的post请求
//构造请求
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());
});
5. 发送文件格式的post请求
const regRequest = {
url : 'https://www.abc.com/aaa/1/storage?key1=value1',
method : 'POST',
header : [{
key : 'token',
value : pm.globals.get("global_token"),
type : 'text'
}],
// header : {
// // 'Content-Type' : 'multipart/form-data',
// token : 'fjkdlsafjkdklajflkdajfkdjakfjdkajfkldajfkldajfkldajfkjdsalkjfdkajfdiafdsafda',
// },
body : {
mode : 'formdata',
formdata : [{
'key' : 'file',
'type' : 'binary',
'src' : '/Users/zhangyang/abc.png'
}]
}
};
pm.sendRequest(regRequest, function (err, response) {
// global_IDCard_front_1 = response.json().result;
console.log(response.json());
});
最后这个没有执行成功,有知道原因的小伙伴评论区留言哈,不胜感激