0


postman使用pre-request script

直接上代码

//预置属性
var SECRET = “”;
var SERVER_SECRET_KEY = ‘’;
var APIKEY_KEY = ‘apiKey’
var apiKey = ‘’;
var seed = 1234;
var nonce = 5678;

//init接口插入全局变量apiKey 其余拿
if (pm.request.url.getPath() === ‘/user/init’) {
apiKey = new Date().valueOf()
pm.globals.set(APIKEY_KEY,apiKey);
}else{
apiKey = pm.globals.get(APIKEY_KEY);
}

//增加query参数
pm.request.addQueryParams(“appid=cece”);
pm.request.addQueryParams(“vs=9.23.2”);
pm.request.addQueryParams(“apikey=”+apiKey);
pm.request.addQueryParams(“agent=ios.cc”);
pm.request.addQueryParams(“lang=zh-CN”);
pm.request.addQueryParams(“appType=cece”);
pm.request.addQueryParams(“channel=huawei”);
pm.request.addQueryParams(“deviceId=doclever”);
pm.request.addQueryParams(“iosidfa=doclever”);
pm.request.addQueryParams(“brand=doclever”);
pm.request.addQueryParams(“model=doclever”);
pm.request.addQueryParams(“network=wifi”);
pm.request.addQueryParams(“carrier=doclever”);
pm.request.addQueryParams(“uuid=docleveruuid”);
pm.request.addQueryParams(“seed=”+seed);

//参数转对象,用于后面验签
var waitSignParams = {};
var urlres= pm.request.url.getQueryString()
urlres = urlres.replace(/&/g, ‘“,”’).replace(/=/g, ‘“:”’);
var reqDataString = ‘{"’ + urlres + ‘"}’;
var query = JSON.parse(reqDataString);

//对象复制
Object.assign(waitSignParams, query);
waitSignParams[‘nonce’] = nonce;

//排序。验签方法
function sort() {
if (pm.method === “POST”) {
waitSignParams[‘body’] = JSON.stringify(body);
};

var sortedKeys = Object.keys(waitSignParams).sort()
var queryStr = '';
sortedKeys.forEach(function (key) {
    if (key !== 'sign') {
        queryStr += key + '=' + waitSignParams[key] + '&';
    }
})

return queryStr.substr(0, queryStr.length - 1);

}

//签名方法
function sign() {
var waitSign = sort() + SECRET;
if (pm.request.url.getPath() === ‘/user/init’) {
return CryptoJS.MD5(waitSign).toString().toUpperCase()
} else {
console.log(CryptoJS.MD5(waitSign)+getServerSecret())
return CryptoJS.MD5(CryptoJS.MD5(waitSign)+getServerSecret()).toString().toUpperCase();
}
}

function getServerSecret() {
return SERVER_SECRET_KEY
}

pm.request.addHeader({key: “Nonce”, value: nonce})

pm.request.addQueryParams(“sign=”+sign());

大概流程:
1.init接口生成apikey存入环境变量
2.login接口讲apikey以及生成的密钥存到数据库
3.用环境变量中的apikey调用其他接口

关于postman的pre-javascript

1.右面有提示,关于预置属性
2.想拿到关于url相关属性用pm.request.url.xxx(eg:pm.request.url.getQueryString())
3.增加参数pm.request.addQueryParams

标签: postman 测试工具

本文转载自: https://blog.csdn.net/qq_21794917/article/details/127678592
版权归原作者 坚持两年 所有, 如有侵权,请联系我们删除。

“postman使用pre-request script”的评论:

还没有评论