【Postman】使用pre-request script进行数据处理

16 篇文章 0 订阅
3 篇文章 0 订阅

项目中需要使用postman模拟业务请求, 每次请求需要

  1. header中生成6位随机字符串nonce
  2. header中生成时间戳timestamp
  3. header中生成签名x-xlx-timestamp = sha1({body}:{timestamp}:{secret}:{nonce})
  4. body
    {
      "op": "create",
      "data": {
        "data_id": dataId, // dataId = md5({timestamp}+{nonce}+{payload}) 
        "sys_time": sysTime // 20210906 11:29:30
      }
    }
    

可以使用Postman提供的Pre-request Script,通过编写js脚本,实现在请求发出前对请求数据进行处理

let nonce = CryptoJS.lib.WordArray.random(3).toString();
let timestamp = new Date().getTime();
// 13位timestimp改为10位
timestamp = Math.floor(timestamp/1000)
// 生成系统时间
let nowTime = new Date();
sysTime = nowTime.getFullYear().toString()+(nowTime.getMonth()+1).toString().padStart(2, '0')+nowTime.getDate().toString().padStart(2, '0') + ' ' + nowTime.getHours().toString().padStart(2, '0') + ':' + nowTime.getMinutes().toString().padStart(2, '0') + ':' + nowTime.getSeconds().toString().padStart(2, '0');
let payload = JSON.stringify({
    sys_time: sysTime
})
let dataIdContent = timestamp + nonce + payload;
// 生成主键
let dataId = CryptoJS.MD5(dataIdContent).toString();
let body = JSON.stringify({
        op: 'create',
        data: {
            data_id: dataId,
            sys_time: sysTime
        }
    })
let secret = 'xxxxxxx';
let signatureContent = body + ':' + timestamp + ':' + secret + ':' + nonce;
// 生成签名
let signature = CryptoJS.SHA1(signatureContent).toString();

// 设置为全局变量
postman.setGlobalVariable("timestamp", timestamp);
postman.setGlobalVariable("nonce", nonce);
postman.setGlobalVariable("signature", signature);
postman.setGlobalVariable("body", body);

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
注:

  1. js中getMonth()获取到的月份比实际月份小1,这是因为月份从0开始计数(真奇葩),所以要获得正确的月份需要手动+1
    参考:
    https://stackoverflow.com/a/18624336/7151777
  2. js中getDate()和getDay()非常容易用乱,前者获取的是几日,而后者获取的是星期几
    参考:
    https://stackoverflow.com/a/13359330/7151777
  3. 获取的月、时、分、秒需要使用.toString().padStart(2, ‘0’)手动补前缀0
    参考:
    https://stackoverflow.com/a/30272803/7151777
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值