首页 > 解决方案 > 获取body的值到变量

问题描述

我有一个场景,我需要将主体值传递给环境变量并在另一个 API 中使用它们。在邮递员

下面是本体,

{
  "firstName" : "Firstname",
  "lastName" : "lastname",
  "email" : "{{timestamp}}@test.com",
  "password" : "{{timestamp}}",
  "country" : 8l16
 }

下面是 Pre-req 脚本,

  postman.setEnvironmentVariable("timestamp", (new 
  Date).getTime());
  // I have copied the Bodyand paste it in a variable called Obj in 
   Pre-req
 // Then i used the below script to get the body
  pm.environment.set("rawBody", JSON.stringify(obj));

但是 timestamp 、 email 和 password 的环境值如下。时间戳值是正确的,其他两个是错误的。

 timestamp = 1566076106769
 email = {{timestamp}}@test.com
  password = {{timestamp}}

时间戳值未在电子邮件和密码中替换,我希望将环境变量值设置为,

预期值,

 email = 1566076106769@test.com
 password = 1566076106769

那么如何将 body 元素值分配给环境/全局变量以在另一个 API 调用中使用?

标签: postmanpostman-collection-runner

解决方案


简单的。您已经设置了环境变量,但从未得到它。"{ }" 在TestsPre-request Script的代码中不起作用。让它像这样:

const timestamp = pm.environment.get('timestamp');
email = `${timestamp} @test.com`; 
password = timestamp;

推荐阅读