postman对请求自动加参(签名)
分类:生产力工具 别名:postman-adds-param-requests-automatically

对接接口时,经常需要调试含签名的接口,如生产环境验签失败则不能返回真实有效数据,而拼接(或排序)正确加密并通过验证,非常耗费精力和时间。

今天突然看了一下postman自带的Pre-request Script工具,发现可以利用起来并实现自动对参数进行签名和加参

在此之前,如果是测试接口,就要到后端去除验签逻辑,如果是正式接口,那就痛不欲生了。

Scripts in Postman:

Postman contains a powerful runtime based on Node.js that allows you to add dynamic behavior to requests and collections. This allows you to write test suites, build requests that can contain dynamic parameters, pass data between requests, and a lot more. You can add JavaScript code to execute during 2 events in the flow:

1.Before a request is sent to the server, as a pre-request script under the Pre-request Script tab.

2 After a response is received, as a test script under the Tests tab.

Pre-request Script是通过Postman的沙盒(Sandbox)来实现的,而Sandbox是一个JavaScript执行环境,里面内置了一部分常用的JS库和函数。

而JavaScript执行环境中的console.log,则是postman自封装的方法,如需查看运行情况,可以呼出postman的console控制台查看。

经过测试,postman是支持ES6语法

Pre-request Script窗口的右侧,提供了几个常用方法:

pm.globals.unset("variable_key");    //清除全局变量

pm.environment.unset("variable_key");    //清除环境变量

pm.globals.get("variable_key");    //获取全局变量

pm.variables.get("variable_key");    //获取一个变量

pm.environment.get("variable_key");    //获取环境变量

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});    //发送一个请求

pm.globals.set("variable_key", "variable_value");    //设置环境变量

如需取得get或post参数,可以查看pm.request对象

{
    "url": {
        "protocol": "https",
        "host": ["liaozixu", "com"],
        "query": [{
            "key": "p",
            "value": "get"
        }],
        "variable": []
    },
    "header": [{
        "name": "Content-Type",
        "key": "Content-Type",
        "value": "application/x-www-form-urlencoded"
    }],
    "method": "POST",
    "body": {
        "mode": "urlencoded",
        "urlencoded": [{
            "key": "p",
            "value": "post www-form"
        }]
    }
}

本文仅举个简单用例,其他用例可以照葫芦画瓢

我需要在get请求中,加入键名为timestamp,值为时间戳的param。

先在参数列表或url中,加入参数占位符

使用postman.setGlobalVariable方法,代替占位符

let timestamp = parseInt(
    (
        new Date().getTime()
    ) / 1000
);
postman.setGlobalVariable(timestamp);

发送请求后,则发出数据为:

/?p=get&timestamp=1581110377
关闭