pm.sendRequest
用于在沙箱 Sandbox 中发送请求。比如你需要测试某类 API 的时候每个请求都需要先发送另一个请求获取某个值后作为请求参数。你就可以在 Collection 或 Folder 的 Pre-requests Script 中使用 sendRequest 函数编写请求发送的代码。
pm.sendRequest
函数允许异步发送 HTTP / HTTPS 请求。简而言之,如果您执行繁重的计算任务或发送多个请求,则可以使用异步脚本在后台执行逻辑。您可以指定一个回调函数并在基础操作完成时收到通知,而不必等待调用完成并阻止下一个请求。
发送简单请求
这里的请求必须要符合 Postman 中的 Collection SDK 的要求。
pm.sendRequest(URL, Function)
:
- 第一个参数以字符串传递 URL
- 第二个实现一个回调函数,回调函数接收两个参数
err
和res
,err 请求失败会接收到的值,res 是请求成功后接收到的响应对象。
比如只是一个 get 请求,可以如下实现(官方示例):
pm.sendRequest('https://postman-echo.com/get', function (err, res) {
if (err) {
console.log(err);
} else {
pm.environment.set("variable_key", "new_value");
}
});
showdoc 案例:
info_url = 'http://127.0.0.1/showdoc/server/index.php?s=/api/user/info'
pm.sendRequest(info_url, function(err, res){
if (err) {
console.log(err); // 如果请求出错,打印错误
} else {
console.log(res.json()); // 打印请求结果
}
});
复杂的请求
复杂的请求,需要通过定义对象的方式把请求中的相关内容全部定义好,官方示例:
// 先定义请求内容
const echoPostRequest = {
url: 'https://postman-echo.com/post',
method: 'POST',
header: 'headername1:value1',
body: {
mode: 'raw',
raw: JSON.stringify({ key: 'this is json' })
}
};
// 将请求内容作为第一个参数传递,第二个参数依然是回调函数。
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
});
showdoc 登录示例:
var loginRequest = {
url: 'http://127.0.0.1/showdoc/server/index.php?s=/api/user/login',
method: 'POST',
header: 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
body: {
mode: 'urlencoded', // 数据格式
urlencoded: 'username=showdoc&password=123456'
}
};
pm.sendRequest(loginRequest, function(err, res){
console.log(err ? err : res.json())
});
这里比较麻烦的是在定义 request 的时候,body 中的数据格式定义:
-
mode
: 指发送的数据格式。一共有四种:raw、formdata、urlencoded、file
- 数据属性,你指定了什么格式,就用什么格式作为属性名。比如这里 mode 用了 urlencoded,那么就以 urlencoded 作为属性名。
再看看如果发送 Json 格式的数据,body 要这样写:
var loginRequest = {
url: 'http://127.0.0.1/showdoc/server/index.php?s=/api/user/login',
method: 'POST',
header: 'application/json', // => header中的格式要指定
body: {
mode: 'raw', // 选择原始
// 传递json字符串数据, 如果是对象格式需要用 JSON.parse 转换
raw: '{"username":"showdoc", "password":"123456"}'
}
};
如果是在 Tests Script 脚本中发送请求,还可以使用 pm.test。达到在一个请求中同时测试多个请求的目的。以下是官方示例。
pm.sendRequest('https://postman-echo.com/get', function (err, res) {
if (err) { console.log(err); } // 请求出错就打印错误信息
pm.test('response should be okay to process', function () { // 测试断言
pm.expect(err).to.equal(null);
pm.expect(res).to.have.property('code', 200);
pm.expect(res).to.have.property('status', 'OK');
});
});
网友评论