0%

Postman前置脚本

基本介绍

Postman的Pre-Request脚本能够很方便的对请求进行一个处理。

在发送request之前,编写pre-request script,定制化request。比如添加随机URL参数,RequestBody的加密等都可以使用pre-Request来实现。

前置登录脚本

在开发过程中经常需要通过token直接调取api,每次登录拿取token都非常麻烦,因此写个脚本在调用接口前拉取登录请求结果塞到环境变量里

解析jwt的代码取自 https://gist.github.com/benhowes/ebf9d2f905d7744e7aa093afe19ddbcd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

var username = '123456'
var password = '123456'

var loginUrl = pm.environment.get("loginApi");

var usr = {

};

pm.sendRequest({
url: loginUrl,
method: 'POST',
header: {
'content-type': 'application/json',
'applicationId': request.headers.applicationid
},
body: {
mode: 'raw',
raw: JSON.stringify({'username': username,
'password':CryptoJS.MD5(password).toString() })

}
},function(err, response) {
const jsonResponse = response.json();
token = jsonResponse.token
var jwt = jwt_decode(token)
usr.userId = jwt.userId;
pm.environment.set("token", token);

});




function jwt_decode(jwt){
var parts = null;
try{
parts = decode_b64(jwt.split('.')[1]);
} catch (e){
console.log("error parsing JWT");
throw (e)
}
console.log(parts)
if (parts){
return JSON.parse(parts);
}
return {};
}

function InvalidCharacterError(message) {
this.message = message;
}

InvalidCharacterError.prototype = new Error();
InvalidCharacterError.prototype.name = 'InvalidCharacterError';

function atob (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
function b64DecodeUnicode(str) {
return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = '0' + code;
}
return '%' + code;
}));
}

function decode_b64(str) {
var output = str.replace(/-/g, "+").replace(/_/g, "/");
switch (output.length % 4) {
case 0:
break;
case 2:
output += "==";
break;
case 3:
output += "=";
break;
default:
throw "Illegal base64url string!";
}

try{
return b64DecodeUnicode(output);
} catch (err) {
return atob(output);
}
};