美文网首页
postman测试接口通过脚本动态设置请求头参数

postman测试接口通过脚本动态设置请求头参数

作者: 爱的旋转体 | 来源:发表于2021-10-29 15:59 被阅读0次

    1、设置环境变量appId和secret


    image.png

    2、设置脚本


    image.png
    const appId = pm.environment.get('appId')
    const secret = pm.environment.get('secret')
    
    const method = pm.request.method
    
    const timestamp = new Date().getTime()
    const randomNum = parseInt((Math.random()*9+1)*100000)
    
    var content = ''
    var param = {}
    var keyArray = []
    
    param['api_time']=timestamp
    param['api_random']=randomNum
    keyArray.push('api_time')
    keyArray.push('api_random')
    
    if("GET" == method){
        const obj = pm.request.url.query.all()
        for(let key in obj){
            if(!obj[key]['disabled']){
                if(obj[key]['value'] != null){
                    param[obj[key]['key']]=obj[key]['value']
                    keyArray.push(obj[key]['key'])
                }
            }
        }
    }else if("POST" == method){
        const requestBody = pm.request.body.raw
        console.log('requestBody', requestBody);
        if(requestBody){
            var obj = JSON.parse(requestBody);
            for(let key in obj){
                var value = obj[key]
                if(value != null && value != ''){
                    param[key]=value
                    keyArray.push(key)
                }
            }
        }
    }
    
    keyArray.sort();
    keyArray.forEach(x => {
        content += x;
        content += '=';
        content += param[x];
        content += '&';
        
    })
    
    content += 'secret=';
    content += secret;
    console.log('content', content);
    const md5 = CryptoJS.MD5(content).toString()
    console.log('md5', md5);
    const Signature = appId + '_' + md5 + '_' + timestamp + '_' + randomNum
    console.log('Signature', Signature);
    
    var signatureName = 'Signature'
    pm.environment.set(signatureName, Signature)
    
    // 添加或修改已存在 header
    pm.request.headers.upsert({
        key: signatureName,
        value: Signature
    })
    

    相关文章

      网友评论

          本文标题:postman测试接口通过脚本动态设置请求头参数

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