TylerBalaskovitz
TylerBalaskovitz

Reputation: 17

Scripting a post response in Bruno as an environment variable

I'm trying to grab data from my response in Bruno and set it to the environment variable called bearer_token. Here's the issue. The response is raw and is just the bearer token. So, I'm not sure what I'm supposed to do to parse the raw response without a body. I have tried to use just res as the data and setting this as the bearer token, but when I check my response, low and behold, the environment variable is still blank. I have attached my Post Response script (the one given by the Bruno documentation), and it doesn't work. Any suggestions would be appreciated.

function onResponse(res) {
let data = res.getBody();
bru.setEnvVar("bearer_token", data);
}

Upvotes: 0

Views: 5508

Answers (3)

TylerBalaskovitz
TylerBalaskovitz

Reputation: 17

This is the answer if it's just a response without any other key-value pairs, but just the bearer token as a response.

   let data =res.body ;
    bru.setEnvVar("token",data);

Upvotes: 0

demiton
demiton

Reputation: 715

Your token is generally a key of your data object (and not the "data" itself), in the "Post Response" field, the following script should work :

let data =res.body ;
bru.setEnvVar("token",data.access_token);

Upvotes: 1

In the modified snippet, the line let data = res.getBody().toString().trim(); now includes the toString() and trim() methods. The toString() method converts the raw response data into a string format, while the trim() method removes any leading or trailing whitespace from the string. These changes ensure the bearer token is properly processed and cleaned before being stored in the bearer_token environment variable.

Upvotes: 1

Related Questions