跳到主要内容

Use Pre-request Script to Dynamically Add a Request Parameter

Usage Scenario

We may need to send some parameters when making a request, and these parameters are calculated from other request parameters. For example:

Interface: https://httpbin.org/anything

The body request parameters are as follows:

ParameterDescription
user_idUser ID
nick_nameUsername

The header request parameters are as follows:

ParameterDescription
tokenComposed of user_id and nick_name from the body request parameters through MD5 encryption

In the above situation, we need to calculate a token from the body request parameters user_id and nick_name through MD5 encryption and put it in the header before sending. How does EchoAPI achieve this requirement?

We can achieve this by adding request parameters in the pre-execution script.

Specific Implementation

As shown in the figure, we have already added the parameters we need in the body.

image.png

1. Calculate the token and assign it to a variable

Next, we need to calculate the token through the pre-execution script and add it to the header parameters.

First, define a temporary variable raw_token in the pre-request script, whose value is

let raw_token = $.md5(request.request_bodys.user_id.toString() + request.request_bodys.nick_name.toString());

The meaning of this is: define a variable raw_token, whose value is equal to

$.md5(request.request_bodys.user_id + request.request_bodys.nick_name)

Note: $.md5 is the MD5 function built into the EchoAPI script. For more encryption functions, please refer to the "Using CryptoJS for MD5/AES Encryption and Decryption of Request Parameters" section.

image.png

2.Dynamically add request headers

pm.setRequestHeader("token", raw_token);

After sending, you can see that EchoAPI automatically added a request header token.

image.png

Appendix: request object

Get request parameters through the request object. For details, please refer to the "EchoAPI Built-in Variables" section of the document.