我不熟悉使用邮递员测试api。我正在尝试获取一个JWT令牌,该令牌可以另存为邮递员中的环境变量。我指的是一篇有关如何做到这一点的出色文章:here
我有下面的python代码,以前曾用它来获取jwt令牌。
import requests
from requests.auth import HTTPBasicAuth
import json
session=requests.Session()
client_id ="abcdef"
secret="ghijklmnop"
token_auth="https://TEST/token"
hed = {'Content-Type': 'application/x-www-form-urlencoded'}
response = session.post(token_auth,headers =hed ,data = 'grant_type=client_credentials',auth = HTTPBasicAuth(client_id,secret),verify = True)
token = json.loads(response.content)['access_token']
print(token)
如何在pm.sendRequest
中编写相同的功能?
答案 0 :(得分:0)
我无法运行此程序,但是您将需要执行以下操作:
const options = {
url: 'https://TEST/token',
method: 'POST',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "client_id", value: "abcdef" },
{ key: "client_secret", value: "ghijklmnop" },
{ key: "grant_type", value: "client_credentials" },
]
}
};
var getToken = true;
if (!pm.environment.get('accessTokenExpiry') ||
!pm.environment.get('currentAccessToken')) {
console.log('Token or expiry date are missing')
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
console.log('Token is expired')
} else {
getToken = false;
console.log('Token and expiry date are all good');
}
if (getToken === true) {
pm.sendRequest(options, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token and expiry date')
var responseJson = res.json();
pm.environment.set('currentAccessToken', responseJson.access_token)
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
});
}