postman使用教程12-预处理发送请求

前言

可以使用 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


作者-上海悠悠

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值