postman使用pre-request-script

简单示例:

//变量定义
let p1='0001';
let p2='0002';
let p3='0003';
let timestamp=Date.parse(new Date());
let signatureStr=CryptoJS.MD5(p2+"&"+p1+"&"+p3+"&"+timestamp).toString();
let signatureKey='@**@@#$!#@%^%@*!!%&^*@!^#$&$#&';
let signature=CryptoJS.MD5(signatureStr+"&"+signatureKey).toString();
//参数管理
pm.globals.set("p1", p1);
pm.globals.set("p2", p2);
pm.globals.set("p3", p3);
pm.globals.set("timestamp", timestamp);
pm.globals.set("signature", signature);
//常用示例
//Get an environment variable
pm.environment.get("variable_key");
//Get a global variable
pm.globals.get("variable_key");
//Get a variable
pm.variables.get("variable_key");
//Get a collection variable
pm.collectionVariables.get("variable_key");
//Set an environment variable
pm.environment.set("variable_key", "variable_value");
//Set a global variable
pm.globals.set("variable_key", "variable_value");
//Set a collection variable
pm.collectionVariables.set("variable_key", "variable_value");
//Clear an environment variable
pm.environment.unset("variable_key");
//Clear a global variable
pm.globals.unset("variable_key");
//Clear a collection variable
pm.collectionVariables.unset("variable_key");
//Send a request
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});


param1:{{p1}}
param2:{{p2}}
param3:{{p3}}
timestamp:{{timestamp}}
signature:{{signature}}

当把Postman的预请求脚本中提供的工具类与具体使用场景相结合时,以下是每个工具类的使用示例:

https://www.postman.com/postman/workspace/postman-answers/request/18070393-0d062245-65cd-4595-aa29-7d52e0591d16

//变量定义
let merchant_no = 1008611;
let params = "{\"merchant_ref\":\"PO20231213061339347bg\",\"system_ref\":\"17097190653SN8B\",\"amount\":\"500.00\",\"pay_amount\":\"500.00\",\"fee\":\"24.00\",\"status\":1,\"success_time\":1709719204,\"extend_params\":\"\",\"product\":\"IndiaPayout\",\"product_ref\":null,\"reason\":\"测试\",\"reversal\":0}"
let timestamp = Number.parseInt(Date.now().toString().slice(0, 10));
let sign_type = 'MD5';
let sign_key = '9834149f-dc31-4e82-96d0-bcd4f1de1b38';
let signStr = merchant_no + params + sign_type + timestamp + sign_key;
let sign = CryptoJS.MD5(signStr).toString();

//参数管理
pm.globals.set("merchant_no", merchant_no);
pm.globals.set("params", params);
pm.globals.set("sign_type", sign_type);
pm.globals.set("timestamp", timestamp);
pm.globals.set("sign", sign);

console.log('----------------------------------request-params-start');
console.log(merchant_no);
console.log(params);
console.log(sign_type);
console.log(timestamp);
console.log(sign);
console.log('------------------------------------request-params-end');

console.log('-----------------ASCII排序加签 begin-------------------');
const obj1 = {
    sign_type: sign_type,
    timestamp: timestamp,
    merchant_no: merchant_no,
    params: params
};
const getSign = (obj) => {
    let signStr = '';
    const keys = Object.keys(obj);
    //ASCII码排序
    keys.sort();
    keys.forEach(key => {
        console.log(`${key}: ${obj[key]}`);
        signStr += `${obj[key]}`
    });
    signStr += sign_key;
    const autoSign = CryptoJS.MD5(signStr).toString();
    return autoSign;
}
console.log('autoSign------->', getSign(obj1));
console.log('-----------------ASCII排序加签 end-------------------');

// console.log('-----------------按照值降序排序 begin-------------------');
// const obj2 = { x: 1, y: 2, z: 3 };
// const keys = Object.keys(obj2);
// //值的从大到小排序
// keys.sort((a, b) => a - b).reverse();
// keys.forEach(key => {
//     console.log(`${key}: ${obj[key]}`);
// });
// console.log('-----------------按照值降序排序 end-------------------');

Get Response Header

// 响应数据存储为全局变量
pm.test("Extract response headers", function () {
    // 将响应头转换为对象
    var headers = pm.response.headers.toObject();

    // 遍历响应头对象
    for (var headerName in headers) {
        // 将响应头名称和值存储在环境变量中
        pm.environment.set(headerName, headers[headerName]);
    }
});

Get Response Body

pm.test("Extract response body", function () {
  // 解析 JSON 响应正文
  var jsonData = JSON.parse(pm.response.text());

  // 检查响应正文是对象还是数组
  if (typeof jsonData === 'object') {
    // 如果是对象,则遍历其属性
    for (var propertyName in jsonData) {
      // 记录属性名称及其值
      console.log(1, propertyName, jsonData[propertyName]);
    }
  } else if (Array.isArray(jsonData)) {
    // 如果是数组,则遍历其元素
    for (var i = 0; i < jsonData.length; i++) {
      // 访问当前元素并遍历其属性
      var element = jsonData[i];
      for (var propertyName in element) {
        // 记录属性名称及其值
        console.log(2, propertyName, element[propertyName]);
      }
    }
  } else {
    // 处理响应正文不是对象或数组的情况
    console.error("Response body is not an object or an array");
  }
});

UUID

for (let i = 0; i < 10; i++) {
    let uuid = pm.variables.replaceIn('{{$guid}}');
    pm.test(`${uuid} is a valid UUID`, () => {
        console.log(uuid);
        pm.expect(uuid).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
    });
}

1、pm

// 设置环境变量
pm.environment.set("key", "value");

// 获取请求信息
var url = pm.request.url;
var method = pm.request.method;
var headers = pm.request.headers;
var body = pm.request.body;

// 处理响应
pm.response.to.have.status(200);
pm.response.to.have.header("Content-Type");
pm.response.to.have.jsonBody();

2、moment

// 解析日期
var date = moment("2022-01-01", "YYYY-MM-DD");

// 格式化日期时间
var formattedDate = moment().format("YYYY-MM-DD");
var formattedDateTime = moment().format("YYYY-MM-DD HH:mm:ss");

// 比较日期时间
var isAfter = moment("2022-01-01").isAfter("2021-12-31");
var isSameOrBefore = moment().isSameOrBefore("2022-12-31");

3、lodash

// 操作数组
var array = [1, 2, 3, 4, 5];
var doubledArray = _.map(array, function(num) {
  return num * 2;
});

// 操作对象
var object = { foo: "bar", baz: "qux" };
var values = _.values(object);
var keys = _.keys(object);

4、xml2js

var xmlParser = require("xml2js").parseString;

// 将XML转换为JavaScript对象
var xml = "<root><name>John Doe</name></root>";
xmlParser(xml, function(err, result) {
  console.log(result.root.name[0]); // 输出: John Doe
});

// 将JavaScript对象转换为XML
var jsObject = { root: { name: ["John Doe"] } };
var builder = new xmlBuilder.Builder();
var xml = builder.buildObject(jsObject);

5、formdata

var formData = new FormData();

// 添加字段数据
formData.append("name", "John Doe");
formData.append("age", 25);

// 序列化FormData
var serializedFormData = formdata.serialize(formData);

6、tv4

var schema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "number" }
  }
};

var data = { name: "John Doe", age: 25 };

// 验证数据与模式是否匹配
var isValid = tv4.validate(data, schema);

// 获取错误信息
var error = tv4.error;

7、csv-parse

var csv = require('csv-parse');

var csvData = 'name,age\nJohn Doe,25\nJane Smith,30';

// 解析CSV数据
csv(csvData, { columns: true }, function(err, records) {
  if (err) {
    console.error(err);
  } else {
    console.log(records);
  }
});

8、xml-escape

var xmlEscape = require('xml-escape');

var xmlString = '<name>John Doe</name>';

// 转义XML字符串中的特殊字符
var escapedXml = xmlEscape(xmlString);

9、xml-builder

var xmlBuilder = require('xmlbuilder');

// 构建XML结构
var xml = xmlBuilder.create('root')
  .ele('name')
  .txt('John Doe')
  .end();

var xmlString = xml.toString();

10、onwebtoken

var jwt = require('jsonwebtoken');

var payload = { username: 'john.doe' };
var secret = 'mysecretkey';

// 生成JWT令牌
var token = jwt.sign(payload, secret);

// 验证JWT令牌
jwt.verify(token, secret, function(err, decoded) {
  if (err) {
    console.error(err);
  } else {
    console.log(decoded);
  }
});

11、query-string

var queryString = require('query-string');

var params = { name: 'John Doe', age: 25 };

// 将对象转换为查询字符串
var queryParams = queryString.stringify(params);

// 将查询字符串解析为对象
var parsedParams = queryString.parse(queryParams);

12、SEncrypt`:

var JSEncrypt = require('node-jsencrypt');

var publicKey = '-----BEGIN PUBLIC KEY-----\n...';
var privateKey = '-----BEGIN PRIVATE KEY-----\n...';

var encrypt = new JSEncrypt();
encrypt.setPublicKey(publicKey);

var ciphertext = encrypt.encrypt('Hello, World!');

var decrypt = new JSEncrypt();
decrypt.setPrivateKey(privateKey);

var plaintext = decrypt.decrypt(ciphertext);

13、os

var os = require('os');

// 获取操作系统平台
var platform = os.platform();

// 获取操作系统架构
var arch = os.arch();

// 获取主机名
var hostname = os.hostname();

// 获取CPU信息
var cpus = os.cpus();

14、crypto-js,x-xss-protection

// 使用crypto-js库进行MD5哈希计算。
var md5Hash = CryptoJS.MD5('Hello, world!').toString();

// 设置X-XSS-Protection标头以启用浏览器的XSS保护。
pm.response.headers.add('X-XSS-Protection', '1; mode=block');

这些示例展示了部分的用法。根据具体的需求和场景,如有需要可以进一步查阅这些工具类的文档,了解更多的详细信息和更广泛的用法。

官方文档:https://learning.postman.com/docs/writing-scripts/pre-request-scripts/

posted @ 2023-12-25 12:42  Journey&Flower  阅读(685)  评论(0编辑  收藏  举报