Postman在pre-request Script中执行登录获取token
1.问题是什么
执行接口需要每次执行登录,然后带入登录的token,需要复制比较麻烦
2.怎么解决
把每次请求发送之前先发送登录请求,然后把登录的token设置到环境变量,最后再把取环境变量的值token
具体代码如下
// 定义发送登录接口请求方法
function sendLoginRequest() {
//定义请求体
var data = {
"mobilePhone":"19900110011",
"verificationCode":"",
"registerWay":"1"
}
// 构造一个 POST raw 格式请求。这里需要改成你们实际登录接口的请求参数。
const loginRequest = {
url: 'https://xxxxxx',
method: 'POST',
header:'Content-Type:application/json',
body: {
mode:'raw',
raw:JSON.stringify(data)
}
};
// 发送请求。
// pm.sendrequest 参考文档: https://www.apifox.cn/help/app/scripts/api-references/pm-reference/#pm-sendrequest
pm.sendRequest(loginRequest, function (err, res) {
if (err) {
console.log(err);
} else {
// 读取接口返回的 json 数据。
// 如果你的 token 信息是存放在 cookie 的,可以使用 pm.cookies.get('token') 方式获取。
// pm.cookies 参考文档:https://www.apifox.cn/help/app/scripts/api-references/pm-reference/#pm-cookies
const jsonData = res.json();
// 将 accessToken 写入环境变量 Authorization
pm.environment.set('Authorization', jsonData.data.token);
}
});
}
// 获取环境变量里的 Authorization
const accessToken = pm.environment.get('Authorization');
// 如 Authorization 没有值,则执行发送登录接口请求
if (!accessToken ) {
sendLoginRequest();
}
好处:不用调用登录请求,一步操作到位。
转自:https://blog.csdn.net/wqchibingshaonian/article/details/109221060