5

I am trying to set an environment variable by capturing a node from the Response Body of an api, where the node contains two hyphenated words.

My script is - postman.setEnvironmentVariable("Token", jsonData.access-token); - This keeps returning ReferenceError: token is not defined

The node in the Response Body is - {"access-token": "<token>"}

I have tried using this script - postman.setEnvironmentVariable("Token", jsonData.access/-/token/); - This script sets the keyword "Token" as an environment key but does not capture the value of the actual token from the Response Body.

Does anyone know the solution to this problem?

2 Answers2

4

ReferenceError: token is not defined

This indicates that token is expected as a distinct variable, but can't be found.

postman.setEnvironmentVariable("Token", jsonData.access-token);

The above statement has invalid JavaScript syntax, as variable/object property names can't have a hyphen within them. More on valid names here: https://mathiasbynens.be/notes/javascript-identifiers

This can be fixed by using the square bracket notation as follows:

pm.environment.set("Token", jsonData["access-token"]);

Note that the postman.* family of functions is deprecated and has been replaced with their pm.* equivalents. More details can be found here: https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference

Kunal Nagpal
  • 776
  • 2
  • 7
  • 14
2

I use this code to get token from response and set it in enviroment variable

const responseJson = pm.response.json();
console.log(responseJson);
if(typeof responseJson.access_token !== 'undefined'){
    pm.environment.set("gateway-access-token", responseJson.access_token);
}
vuhoanghiep1993
  • 715
  • 1
  • 8
  • 15