Postman使用指北

Posted by Solejay on Fri, Aug 23, 2024

粘贴 cURL 请求

1724381954004_1h4gs23llx

环境设置

作用:方便切换不同环境,比如配置本地环境/测试环境/线上环境,通过切换环境就可以请求对应环境的接口

  • 配置环境

1724382099854_p4knk4pld8

  • 切换环境请求

1724382191899_srz1hh2woj

Pre-request Script

可以在发送请求之前执行一些脚本操作

1. 常用指令

 1// 获取请求方法
 2pm.request.method
 3
 4// 设置 header
 5pm.request.headers.add({
 6    key: 'key',
 7    value: 'value'
 8});
 9
10// 设置 cookie
11pm.request.headers.add({
12    key: 'Cookie',
13    value: "cookie_value"
14});

2. 请求鉴权

后端为了服务接口不被恶意攻击,一般会有鉴权的校验,比如在 header 头中加入 tsnonce 等,就可以在 postman 中通过 pre-request script 统一封装起来进行调用

示例代码

 1function randomString(e) {    
 2    e = e || 32;
 3    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
 4    a = t.length,
 5    n = "";
 6    for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
 7    return n
 8}
 9
10function getParam(body) {
11    var keys = [];
12    for (let k in body) {
13        let value = body[k];
14        if (Array.isArray(value)) {
15            value = JSON.stringify(value);
16        }
17        keys.push(k + "=" + value);
18    }
19    keys.sort();
20    let keys_str = keys.join("&");
21    return keys_str;
22}
23
24var app = "app"
25var secret = "key"
26var ts = Math.round (new Date().getTime()/1000)
27var nonce = randomString(16)
28var param = ""
29if (pm.request.method === "POST") {
30    param = getParam(JSON.parse(request.data))
31}
32
33pm.request.headers.add({
34    key: 'app',
35    value: app
36});
37pm.request.headers.add({
38    key: 'ts',
39    value: ts
40});
41pm.request.headers.add({
42    key: 'nonce',
43    value: nonce
44});
45console.log(app+secret+ts+param+nonce)
46pm.request.headers.add({
47    key: 'sign',
48    value: CryptoJS.MD5(app+secret+ts+param+nonce).toString()
49});

3. 在 json 请求体中写注释

postman 没有很好的写接口注释的地方,对于 post 请求无法直接在参数后面写注释(不符合 json 规范),通过脚本的方式达到既写注释又可以发送请求的目的

1// 需要在Pre-request Script中这样写,去除掉注释
2if (pm?.request?.body?.options?.raw?.language === 'json') {
3    const rawData = pm.request.body.toString();
4    const strippedData = rawData.replace(
5        /\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g,
6        (m, g) => g ? "" : m
7    );
8    pm.request.body.update(JSON.stringify(JSON.parse(strippedData)));
9}

1724382856856_jtnmtuhgyq

Get 请求 Encode

在发送 get 请求时,可以右键参数 encode 请求,方便发送

1724382983052_773f7f7a17

参考链接

Postman 高级用法