美文网首页PostManPostman教程postman
在Postman脚本中发送请求(pm.sendRequst)

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

作者: 韩志超 | 来源:发表于2019-02-19 01:21 被阅读8次

    Postman的Collection(集合)/Folder(集合的子文件夹)/Request(请求)都有Pre-request script和Tests两个脚本区域, 分别可以在发送请求前和请求后使用脚本(基于Javascript实现各种操作)


    集合的脚本区 文件夹的脚本区 请求的脚本区

    在遇到有依赖的接口时,比如需要登录或者需要从前一个接口的结果中获取参数时,我们往往需要在该请求前先发送一下所依赖的请求, 我们可以在Pre-request script中使用pm.sendRequest实现

    1. 发送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请求
    1. 发送表单格式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表单请求
    1. 发送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请求
    1. 发送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());
    });
    
    

    本文所演示接口- 接口文档传送门

    相关文章

      网友评论

        本文标题:在Postman脚本中发送请求(pm.sendRequst)

        本文链接:https://www.haomeiwen.com/subject/ooltyqtx.html