• postman使用教程12-预处理(pre-request) 发送请求


    前言

    可以使用 pm.sendRequest 方法从“pre-request”或“Tests”脚本异步发送请求。
    如果您要执行计算或同时发送多个请求,而不必等待每个请求完成,则可以在后台执行逻辑。

    pre-request 发送请求

    点 Send a request 快速生成一个请求示例

    • pm.sendRequest 是发送一个请求
    • function中的err表示请求返回的错误信息,
    • response表示响应内容
    • console.log()是控制台输出日志
    pm.sendRequest("https://postman-echo.com/get", function (err, response) {
        console.log(response.json());
    });
    
    

    发送一个post请求示例

    // Example with a full-fledged request
    const postRequest = {
      url: 'https://postman-echo.com/post',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'X-Foo': 'bar'
      },
      body: {
        mode: 'raw',
        raw: JSON.stringify({ key: 'this is json' })
      }
    };
    pm.sendRequest(postRequest, (error, response) => {
      console.log(error ? error : response.json());
    });
    

    参数说明:

    • const是js中用来定义变量的关键字,由const定义的变量不可以修改,而且必须初始化
    • url表示要发送的请求url地址;
    • method指定请求方法 GET/POST;
    • header定制请求头信息,传json格式的数据的话,需定义请求头为Content-Type:application/json
    • body 表示post请求body参数
    • JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个JSON字符串

    更多示例

    以下是官方文档给的示例https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/

    // Example with a plain string URL
    pm.sendRequest('https://postman-echo.com/get', (error, response) => {
      if (error) {
        console.log(error);
      } else {
      console.log(response);
      }
    });
    
    // Example with a full-fledged request
    const postRequest = {
      url: 'https://postman-echo.com/post',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'X-Foo': 'bar'
      },
      body: {
        mode: 'raw',
        raw: JSON.stringify({ key: 'this is json' })
      }
    };
    pm.sendRequest(postRequest, (error, response) => {
      console.log(error ? error : response.json());
    });
    
    // Example containing a test
    pm.sendRequest('https://postman-echo.com/get', (error, response) => {
      if (error) {
        console.log(error);
      }
    
      pm.test('response should be okay to process', () => {
        pm.expect(error).to.equal(null);
        pm.expect(response).to.have.property('code', 200);
        pm.expect(response).to.have.property('status', 'OK');
      });
    });
    

    请求定义和响应结构参考文档

    Request 请求参数参考文档[http://www.postmanlabs.com/postman-collection/Request.html#~definition]

    Response 返回参考文档http://www.postmanlabs.com/postman-collection/Response.html


    作者-上海悠悠 blog地址 https://www.cnblogs.com/yoyoketang/

  • 相关阅读:
    python --异常处理
    Python -- 函数对象
    python --循环对象
    python --循环设计
    python --模块
    python --文本文件的输入输出
    xpee.vbs
    oracle 有个xe版本
    POI对Excel单元格进行颜色设置
    POI进行ExcelSheet的拷贝
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/14753128.html
Copyright © 2020-2023  润新知