最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting response from Postman in script - Stack Overflow

programmeradmin2浏览0评论

I 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

I 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
Share Improve this question edited Jan 20, 2020 at 13:18 Angels asked Jan 20, 2020 at 12:03 AngelsAngels 3554 silver badges18 bronze badges 1
  • Does this answer your question? There was an error in evaluating the Pre-request Script – Henke - Нава́льный П с м Commented Jan 26, 2021 at 12:22
Add a ment  | 

3 Answers 3

Reset to default 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)

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) 

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./docs/postman/variables-and-environments/variables/#defining-variables-in-scripts

发布评论

评论列表(0)

  1. 暂无评论