当前位置:   article > 正文

Postman进阶(一):编写预请求脚本(pre-request scripts)_postman预请求脚本

postman预请求脚本

一:在请求运行之前编写脚本

1.点击集合中的任意一个接口

2.点击Pre-request Script,即可在此下方编写脚本

3.点击send,Pre-request Script下的代码将在Postman将请求发送到API之前执行

二:如何编写脚本

Postman中提供一些选项,点击一下,则会在Pre-request Script中生成对应的脚本,可根据自己的需求来编写脚本

  1. 点击集合中的任意一个接口
  2. 点击Pre-request Script,即可在此下方编写脚本
  3. 点击右侧的Snippets下的提示

  1. //获取环境变量
  2. pm.environment.get("variable_key");
  3. //获取全局变量
  4. pm.globals.get("variable_key");
  5. pm.variables.get("variable_key");
  6. //获取集合变量
  7. pm.collectionVariables.get("variable_key");
  8. //设置具有指定名称和值的环境变量
  9. pm.environment.set("variable_key", "variable_value");
  10. //设置具有指定名称和值的全局变量
  11. pm.globals.set("variable_key", "variable_value");
  12. 设置具有指定名称和值的集合变量
  13. pm.collectionVariables.set("variable_key", "variable_value");
  14. //清除环境变量
  15. pm.environment.unset("variable_key");
  16. //清除全局变量
  17. pm.globals.unset("variable_key");
  18. //清除集合变量
  19. pm.collectionVariables.unset("variable_key");
  20. //发送请求
  21. pm.sendRequest("https://postman-echo.com/get", function (err, response) {
  22. console.log(response.json());
  23. });

示例:

  1. //获取全局变量my_variable
  2. var test = pm.globals.get("my_variable");
  3. console.log('my_variable的值:' + test)
  4. //设置全局变量newTest的值为获取全局变量my_variable的值
  5. pm.globals.set("newTest", test);

三:使用请求数据编写脚本

pm.request对象提供对运行脚本的请求的数据的访问。对于预请求脚本这是即将运行的请求

可以使用pm.request对象预请求脚本在请求运行之前更改请求配置的各个部分。

pm.request对象提供以下属性和方法:

  • 为当前请求添加具有指定名称和值的标头:
pm.request.headers.add(header:Header):function

示例:

  1. pm.request.headers.add({
  2. key:"client-id",
  3. value:"abcdef"
  4. })

如:在Postman中的预请求脚本中,添加上述示例代码,打开控制台,在该请求接口中看到headers中新增了我们设置的key和value

  • 删除指定名称的请求头:
pm.request.headers.remove(headerName:String):function

示例:

pm.request.headers.remove("client-id");

如:上述在headers中添加了key和value,在下面我们选择删除数据,在预请求脚本中添加上述代码,在控制台中则会发现,不会出现新增的key和value

四:从脚本中发送请求

在上述中的脚本中,postman中最下方有提示语句,在预请求脚本中发送一个请求,可用于在创建的接口前先调用一个需要用到的接口,并对该接口的响应数据做处理

示例:调用接口,并将调用的响应结果中的某个参数,放在环境变量中

  1. const postRequest = {
  2. url: 'https://postman-echo.com/post',
  3. method: 'POST',
  4. header: {
  5. 'Content-Type': 'application/json',
  6. 'X-Foo': 'bar'
  7. },
  8. body: {
  9. mode: 'raw',
  10. raw: JSON.stringify({ key: 'test' })
  11. }
  12. };
  13. pm.sendRequest(postRequest, (error, response) => {
  14. console.log(error ? error : response.json());
  15. var test = response.json();
  16. var newKey = test.data.key;
  17. pm.collectionVariables.set("newKey", newKey);
  18. });

在postman中的预请求脚本写入此代码,点击send

点击集合中的变量,能看到执行的将newKey放入在了集合变量中

自己动手试试叭~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/898516
推荐阅读
相关标签
  

闽ICP备14008679号