2

image attachedI want to get the value of token from response of Postman and set it to an environment.

My response is showing like :

{
  "success": true,
  "token": "ojkdd"
}

and my script is :

pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody);
console.log(jsonData)

I get the following error :

ReferenceError: responseBody is not defined
1

3 Answers 3

5

your json data is in pm. So you need to retrieve your JSON data using the below code.

 var jsonData = pm.response.json(); 

 pm.test("Verify Json values", function () { 
  pm.expect(jsonData.success).is.to.equal(true); 
 });

Edit : For setting it to environment as @danny suggested

 pm.environment.set("token", pm.response.json().token)
8
  • Thanks, I get the following error from the first line: "TypeError: Cannot read property 'json' of undefined"
    – Angels
    Commented Jan 20, 2020 at 12:40
  • did you console.log(pm.response.json().token) ? Sometimes the environment would be set even though postman throws undefined error. Commented Jan 20, 2020 at 12:51
  • screenshot attached in question.
    – Angels
    Commented Jan 20, 2020 at 13:19
  • 1
    You can only use pm.response.json() in the Tests tab as that's when it would know what the response will be. The items in the Pre-request Script tab get actioned before the main request is sent. Commented Jan 20, 2020 at 13:56
  • 1
    No, you can only use the pm.response.json() function in the Tests tab of the app. It will not work in the Pre-request Script tab. Commented Jan 20, 2020 at 19:26
2

You did this same wrong way as I today :D the script should be in test not in Pre-request Sript

For response: { "token" : "kj32n4jk32n4" }

Past below script to TEST tab in postman and debug it in postman console

var data = JSON.parse(responseBody)
console.log(data.token)
postman.setEnvironmentVariable('token',data.token) 
1
  • is that your own token ?
    – Elikill58
    Commented Jan 27, 2022 at 17:49
1

If you want to store the value as an environment variable, you can add this to the Tests tab:

pm.environment.set("token", pm.response.json().token)

You will need to ensure that you have created an environment file and it's selected in the top right of the UI, before the variable can be stored.

More information about storing variables can be found here:

https://learning.getpostman.com/docs/postman/variables-and-environments/variables/#defining-variables-in-scripts

Not the answer you're looking for? Browse other questions tagged or ask your own question.