美文网首页Postman中文文档
Postman Pre-request Scripts 请求之前

Postman Pre-request Scripts 请求之前

作者: sologuy | 来源:发表于2019-06-12 21:48 被阅读2次

    按照如下脚本即可:

    
    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());
            }
        });
    }
    

    相关文章

      网友评论

        本文标题:Postman Pre-request Scripts 请求之前

        本文链接:https://www.haomeiwen.com/subject/jworfctx.html