如何在Thunder Client中实现Postman的API响应保存与数据处理
在Thunder Client中实现Postman的响应数据处理与环境变量存储
1. 处理TIN字符串去空格并存入环境变量
Postman中是解析响应体后去除空格存入变量,在Thunder Client里,直接在请求的Tests标签下写以下代码即可:
// 获取API返回的纯文本响应 const tinWithSpaces = response.text(); // 移除所有空格 const tinClean = tinWithSpaces.replace(/\s/g, ''); // 将处理后的值存入环境变量tin tc.setVar("tin", tinClean, "env");
如果响应文本带首尾引号(比如返回"21 348 504 760"),先去掉引号再处理:
const tinWithSpaces = response.text().replace(/^"|"$/g, ''); const tinClean = tinWithSpaces.replace(/\s/g, ''); tc.setVar("tin", tinClean, "env");
你之前的问题大概率是没正确获取响应内容,直接把未执行的函数逻辑存进了变量,要确保是执行replace后的结果赋值。
2. 处理positions字段生成格式化字符串并存入变量
对应Postman的逻辑,在Thunder Client的Tests标签下用以下代码实现:
// 把响应体解析为JSON对象 const jsonData = response.json(); // 提取positions字段转为字符串 let positionstring = "" + jsonData.positions; // 生成无逗号的pwd字符串 const pwdstring = positionstring.replace(/,/g, ''); // 生成带引号包裹的数组格式字符串 positionstring = positionstring.replace(/,/g, '","'); positionstring = `["${positionstring}"]`; // 将两个值分别存入环境变量 tc.setVar("positions", positionstring, "env"); tc.setVar("pwd", pwdstring, "env");
注意:Thunder Client用tc.setVar设置环境变量,和Postman的pm.environment.set语法不同;获取响应内容时,JSON格式用response.json(),纯文本用response.text()。
内容的提问来源于stack exchange,提问作者user3717796
相关产品推荐
相关产品推荐

