pm.sendRequest的作用就是发送一个请求,并获取其他的返回信息。

     pm.sendRequest可以在pre-Request Script 和Test模块中使用。

    以下几种是:

         1、发送get请求示例

         2、发送json格式的Post请求示例

         3、发送表单格式的Post请求示例

pm.sendRequest默认是不带参数的Get请求:

const url ="https://postman-echo.com/get"
pm.sendRequest(url, function (err, response) {  // 参数1是request请求信息,参数2是请求回调返回的数据。
    console.log(response.json());
});

使用pm.sendRequest发送JSON 格式的Post请求:

const regRequest = {
  url: 'http://XXXX',
  method: 'POST',
  header: 'Content-Type: application/json',  //注意要在Header中声明内容使用的类型
  body: {
    mode: 'raw',  // 使用raw(原始)格式
    raw: JSON.stringify({ name: 'Test', password: '123456' }) //要将JSON对象转为文本发送
  }
};


//发送请求
pm.sendRequest(regRequest, function (err, res) {
  console.log(err ? err : res.json());  // 响应为JSON格式可以使用res.json()获取到JSON对象
});

使用pm.sendRequest发送JSON 格式的Post请求:

//构造一个登录请求
const loginRequest = {
    url: 'http://XXXX',
    method: "POST",
    body: {
        mode: 'urlencoded',  // 模式为表单url编码模式
        urlencoded: 'name=张三&password=123456'
    }
};


// 发送请求
pm.sendRequest(loginRequest, function (err, res) {
    console.log(err ? err : res.text());
});

使用pm.sendRequest发送JSON 发送XML格式请求:

//构造请求
const demoRequest = {
  url: 'http://XXXX',
  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());
});


-------------------------------------最后---------------------------------

 更多软件测试相关内容请关注“软件测试道与术”公众号或扫描下方二维码

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐