How do I get the real data of environment variables in pre-req?

I have a pre-req script that does md5 encryption and then passes it back to the server, and when the data is a variable, what is encrypted is the variable name, not the real data of the variable. How to deal with it?

Here’s an example of a request👇

variable

pre-req script

variable testmd5 = “hello!world”

Expected :man_technologist:t2:

const testMd5 =MD5("hello!world")
// output: "4B460DD7310C9F783242F2809CDFC2EE"

Actually :face_with_diagonal_mouth:

const testMd5 =MD5("{{testmd5}}")
//output: "f5fa842484de91794470c780b167183c"

Hey @GreenKing19 :wave:t3:

Welcome to the Postman Community :postman:

As you’re extracting that raw string from the request body, it’s just using the string value of the variable before it’s been resolved.

You’d need to use something like:

const MD5 = require('crypto-js').MD5;

const requestData = JSON.parse(pm.request.body.raw)
const testmd5 = requestData.testmd5
const md5String = MD5(pm.variables.replaceIn(testmd5)).toString()

console.log(md5String);

How are you setting that newly converted string in the request body?

Pretty much what Danny has said.

const MD5 = require('crypto-js').MD5
let myVar = pm.variables.get("testmd5"); // or pm.environment.get
const md5String = MD5(myVar).toString();
console.log(md5String);

image

What do you mean by “pass it back to the server”. Do you need to update the value of the environment variable with the encrypted string? (Which is easy enough, just add pm.environment.set to the end of the script).

I know this way, but sometimes I don’t know what the variable name is, because my pre-req is written inside the collection.
Sometimes it’s a variable, sometimes it’s an environment variable
:confounded:

Is it at least the same name each time?

If you use pm.variables, it will get the variable with the narrowest scope.

let myVar = pm.variables.get("testmd5"); // or pm.environment.get

Postman Variable Scopes | Postman Learning Center

So it will be this order.

Local → Data → Environment → Collection → Global - Postman

If you only have the variable set as an environment variable, then it will be fine. If you have the variable with the same name set in multiple locations, then it will read the narrowest value. So a local variable will take precedence over an environment variable if they have the same name.

1 Like