You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Postman测试脚本问题:请求后打印指定格式字符串失败

解决Postman获取请求体字段失效并打印指定格式内容的方案

为什么pm.request.json().field_name会失效?

  • 请求体不是JSON格式(比如用了form-data、x-www-form-urlencoded)
  • 字段名拼写/大小写和请求体里的实际字段不匹配
  • 请求体为空或根本没有目标字段

分步解决代码

1. 正确获取请求体字段(兼容多种格式)

let requestField;
try {
    // 先尝试解析JSON格式请求体
    const reqJson = pm.request.json();
    requestField = reqJson.your_request_field; // 替换成你的实际请求字段名
} catch (err) {
    console.log("JSON解析失败,尝试其他格式:", err.message);
    // 若为form-data格式
    // requestField = pm.request.body.formdata.get("your_request_field");
    // 若为x-www-form-urlencoded格式
    // requestField = pm.request.body.urlencoded.get("your_request_field");
    // 若为原始文本格式
    // requestField = pm.request.body.raw;
}

2. 获取响应字段

let responseField;
try {
    const resJson = pm.response.json();
    responseField = resJson.your_response_field; // 替换成你的实际响应字段名
} catch (err) {
    console.log("响应JSON解析失败:", err.message);
    // 若响应是纯文本
    // responseField = pm.response.text();
}

3. 拼接格式并打印

// 获取当前毫秒级时间戳,要秒级就用Math.floor(Date.now()/1000)
const timeStamp = Date.now();
// 拼接成你要的格式
const outputStr = `${requestField}, ${responseField}, ${timeStamp}.`;
// 打印到Postman控制台
console.log(outputStr);

调试小技巧

  • 先打印原始请求/响应体,确认字段存在:
    console.log("原始请求体:", pm.request.body.raw);
    console.log("原始响应体:", pm.response.text());
    
  • 严格检查字段名的大小写,JSON是大小写敏感的

内容的提问来源于stack exchange,提问作者mb334

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:26:01