一、.需求1:
postman可以在接口请求Pre-request 添加请求前的操作,很多接口都是依赖于先登录的。于是可以在Pre-request 发送一个登录请求获取token。
添加请求的代码:
这里在获取token之后更新到请求头部,有两种写法:
写法1:
const loginRequest = {
url: 'http://xxx',
method: 'POST',
header:
['Content-Type: application/json',
'source: xxx',
],
//没有source可以不填,去掉大括号
body: {
mode: 'raw',
raw: JSON.stringify({ username: 'xxx', password: 'xxx' })
}
};
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
// 将 token 写入环境变量
const token = res.json().result.token;//我的请求返回token在result下 所以有result.token,若你的请求直接是token,直接写token就可
pm.environment.set('token', token);
//更新到请求头部
pm.request.headers.add({
key:"token",
value:"{{token}}"})
}})
写法2:
const loginRequest = {
url: 'http://xxx',
method: 'POST',
header:
['Content-Type: application/json',
'source: xxx',
],
body: {
mode: 'raw',
raw: JSON.stringify({ username: 'xxx', password: 'xxx' })
}
};
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
// 将 token 写入环境变量
const token = res.json().result.token;
pm.environment.set('token', token);
const token1 = pm.environment.get('token')
//更新到请求头部
pm.request.headers.add({
key:"token",
value:"token1"})
}})
写好后send一下,就OK啦
二、需求2:
当接口较多的时候,每个接口前面加一次会很麻烦,这种公共操作可以写到collection 集合中添加 Pre-request Scripts
collection添加Pre-request Scripts
代码如下:
const loginRequest = {
url: 'http://xxx',
method: 'POST',
header:
['Content-Type: application/json',
'source: xxx',
],
//没有source可以不填,去掉大括号
body: {
mode: 'raw',
raw: JSON.stringify({ username: 'xxx', password: 'xxx' })
}
};
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
// 将 token 写入环境变量
const token = res.json().result.token;//我的请求返回token在result下 所以有result.token,若你的请求直接是token,直接写token就可
pm.environment.set('token', token);
//更新到请求头部
pm.request.headers.add({
key:"token",
value:"{{token}}"})
}})
这样在其下添加一个请求,send后就可以不用在header里引用{{token}}或者直接填写token啦,这样很简单啦
搞了好久,百度了好久,应该非常有用的,欢迎指正~
文章参考:https://blog.csdn.net/wqchibingshaonian/article/details/109221060
https://blog.51cto.com/u_15249893/4541441