搜索
您的当前位置:首页正文

在Postman脚本中发送请求(pm.sendRequest)

来源:小奈知识网

 

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()); }); 

 

 
 
 

例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)
});

 

转载于:https://www.cnblogs.com/But-you/p/11219481.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Top