kagxin / blog

个人博客:技术、随笔、生活
https://github.com/kagxin/blog/issues
7 stars 0 forks source link

postman发起请求时添加token #32

Open kagxin opened 5 years ago

kagxin commented 5 years ago

如何添加token

1、以编辑一个collection为例,设置header中的Authorization字段

image

image

2、如何在 Pre-request Script中添加请求获取token

有时候,我们想在每次请求之前都获取一次token,Pre-request Script会在发生请求之前执行

pm.sendRequest({    // pm.sendRequest 发一次http请求
    url: "http://"+pm.variables.get('host')+"/api/v1/account/login/", //请求地址
    method: 'POST',  // 方法
    header: {
        'content-type': 'application/json',  // 格式
        'accept': 'application/json',
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({login_name:pm.variables.get('username') , password: pm.variables.get('password')})  // body json 格式,username和password字段
    }
}, function (err, res) {  // http回调函数
    // pm.environment.set("token", "token " + res.json().data.access_token);  //设置环境变量
    pm.request.headers.add({    //设置header Authorization: token  <?token>
        key: 'Authorization',
        value: "token " + res.json().data.access_token
    });
});
//

image