通过postman的Pre-request Script 可以实现参数验签。
Pre-request Script是基于 Node.js 的强大运行时,它允许我们向请求和集合中添加动态行为。允许我们编写 API 测试、构建可以包含动态参数的请求、在请求之间传递数据等等。您可以添加两种情况下的 JavaScript 代码:
- 在请求发送到服务器之前,在“Pre-request Script”选项卡中编写预请求脚本;
- 收到响应后,在 “ Test”选项卡中编写测试脚本。
参考文档: https://postman.org.cn/writing-scripts/intro-to-scripts/
image.png
完整脚本:
const uuid = require("uuid")
function getTimestamp(){
var time=new Date().getTime();
pm.environment.set("time", time);
return time;
}
function getRandom(){
var random= uuid.v4().replace(/-/g, '');
pm.environment.set("uuid", random);
return random;
}
function getSign(){
var random = getRandom();
var body = pm.request.body.raw;
var str= body+ random;
var sign = CryptoJS.MD5(str).toString().toLowerCase();
sign = sign.slice(0, 10) + random + sign.slice(-22);
console.log(sign);
console.log(random);
console.log(time);
return sign;
}
pm.request.headers.add({key: 'x-sign',value: getSign()});
pm.request.headers.add({key: 'x-source',value: 'postman'});
//将其他header添加到请求头
Object.keys(request.headers).forEach(key => {
console.log(key);
pm.request.headers.add({key: key,value:request.headers[key]});
});
Pre-request Script | 外部库的使用
https://juejin.cn/post/7214005088510394428
header操作
// 添加新 header
pm.request.headers.add({key: 'Accept-Encoding',value: 'gzip'});
// 添加或修改已存在 header
pm.request.headers.upsert({key: 'Connection',value: 'close'});
// 移除 header
pm.request.headers.remove('User-Agent')
获取body
pm.request.body.raw
获取body中的password参数
var body = pm.request.body.raw
var body_json = JSON.parse(body)
pwd = body_json["password"]
console.log(pwd) 在console打印pwd参数