如何在 PostMan 的预请求脚本中计算 md5 哈希?

2022-01-22 00:00:00 hash md5 postman javascript

我必须在我的请求中设置一个参数,该参数是其他两个参数的 md5 哈希.我认为预请求脚本可以完成这项工作,但我不知道如何在这个脚本中计算 md5.有什么想法吗?

解决方案

如果您的参数是定义的环境变量,您可以创建以下预请求脚本.如果以其他方式定义它们,则需要调整此示例.

//像这样访问你的环境变量var str_1 = environment.variable_1 + environment.variable_2;//或者获取你的请求参数var str_2 = request.data["foo"] + request.data["bar"];//使用 CryptoJSvar hash = CryptoJS.MD5(str_1 + str_2).toString();//设置新的环境变量postman.setEnvironmentVariable('hash', hash);

CryptoJS 之所以有效,是因为它在 Postman(以及 lodash、backbone 等)中可用.

通过 environment 对象可以轻松访问环境变量.

通过 postman 对象可以设置环境变量.

在此预请求运行后,您可以使用普通的 {{hash}} 简写访问 hash 变量.

此外,您还可以阅读此处了解 Postman 中可用的库、变量和属性.p>

I have to set a parameter in my request that is a md5 hash of two other parameters. I think a pre-request script can do the job, but I do not know how to compute a md5 in this script. Any idea?

解决方案

You can create the following pre-request script provided your parameters are defined environment variables. You would need to tweak this example if they are defined in some other fashion.

// Access your env variables like this
var str_1 = environment.variable_1 + environment.variable_2;

// Or get your request parameters
var str_2 = request.data["foo"] + request.data["bar"];

// Use the CryptoJS
var hash = CryptoJS.MD5(str_1 + str_2).toString();

// Set the new environment variable
postman.setEnvironmentVariable('hash', hash);

CryptoJS works because it's available in Postman (as well as lodash, backbone etc).

Accessing environment variables is easy through the environment object.

Setting environment variables is available through the postman object.

After this pre-request has run you can access the hash variable using the normal {{hash}} shorthand.

Also, you can read here about libraries, variables and properties available in Postman.

相关文章