Postman中文文档

Postman Pre-request Scripts 请求之前

2019-06-12  本文已影响2人  sologuy

按照如下脚本即可:


url = pm.environment.get("baseurl");
const echoPostRequest = {
  url: `${url}/login`,
  method: 'POST',
  header: 'Content-Type:application/json',
  body: {
    mode: 'application/json',
    raw: JSON.stringify({
        username: '18000000000',
        password: '123456'
    })
  }
};
var getToken = true;

if (!pm.environment.get('accessTokenExpiry') || 
    !pm.environment.get('id_token')) {
    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(echoPostRequest, function (err, res) {
        console.log(err ? err : res.json());
        if (err===null){
           var responseJson = res.json();
            pm.environment.set("id_token", responseJson.id_token);
            var expiryDate = new Date();
             console.log('Saving the token and expiry date');
            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
            pm.environment.set('accessTokenExpiry', expiryDate.getTime());
        }
    });
}
上一篇下一篇

猜你喜欢

热点阅读