Pre-request Script in Postman on Ubuntu: A Step-by-Step Guide
Pre-request scripts in Postman are JavaScript code snippets that execute before sending an API request. They are commonly used to dynamically set variables (e.g., tokens, timestamps), modify request headers/parameters, or send preliminary requests to prepare data for the main call. Below is a structured guide to using pre-request scripts in Postman on Ubuntu.
1. Install Postman on Ubuntu
Before using pre-request scripts, ensure Postman is installed. You can choose one of three methods:
- Snap (Recommended): Open terminal and run
sudo snap install postman --classic. - Manual Download: Download the Linux package from Postman’s website, extract it with
tar -xzf Postman-linux-x64-*.tar.gz -C /opt, and create a desktop shortcut. - Package Manager: Add Postman’s PPA (
sudo add-apt-repository https://dl.bintray.com/postman/apt), update (sudo apt update), and install (sudo apt install postman).
After installation, launch Postman from the application menu or terminal (postman).
2. Access Pre-request Script Editor
To add a pre-request script to a request:
- Open Postman and select an existing request or create a new one (click “+” in the top-left corner).
- In the request editor, navigate to the Pre-request Script tab (located above the “Tests” tab). This is where you’ll write your script.
3. Write Common Pre-request Script Examples
Pre-request scripts leverage the pm object (Postman’s scripting API) to interact with requests and variables. Below are practical examples:
a. Generate Dynamic Variables
Use pm.environment.set() or pm.globals.set() to store dynamic values (e.g., random strings, timestamps) for use in the request or subsequent scripts.
// Generate a 10-character random string (letters + numbers)
const randomStr = Math.random().toString(36).substr(2, 10);
pm.environment.set("randomParam", randomStr);
// Generate a timestamp (seconds since epoch)
const timestamp = Math.floor(Date.now() / 1000);
pm.globals.set("requestTimestamp", timestamp.toString());
These variables can be referenced in the request URL, headers, or body using {{variable_name}} (e.g., {{randomParam}}).
b. Set Request Headers
Modify the request headers before sending. For example, add an Authorization header with a Bearer token (stored in an environment variable):
const token = pm.environment.get("authToken");
pm.request.headers.add({
key: "Authorization",
value: `Bearer ${token}`
});
This ensures the token is included in the request without hardcoding it.
c. Send a Preliminary Request
Use pm.sendRequest() to call an external API (e.g., to fetch a token) and store the response in a variable.
const getTokenRequest = {
url: "https://api.example.com/auth",
method: "POST",
header: {
"Content-Type": "application/json"
},
body: {
mode: "raw",
raw: JSON.stringify({ username: "user", password: "pass" })
}
};
pm.sendRequest(getTokenRequest, (error, response) => {
if (error) {
console.error("Error fetching token:", error);
} else {
const token = response.json().access_token;
pm.environment.set("authToken", token); // Store token for main request
}
});
The main request will wait for this script to finish before executing.
d. Modify Request Body
Dynamically generate the request body (e.g., JSON payload with current timestamp).
const requestBody = {
userId: 123,
action: "login",
timestamp: new Date().toISOString()
};
pm.request.body.raw = JSON.stringify(requestBody);
This is useful for APIs that require up-to-date data in the request body.
4. Save and Execute the Script
- Save: Click the “Save” button (floppy disk icon) in the top-left corner to save your request (including the pre-request script).
- Execute: Click the “Send” button (blue arrow) to run the request. The pre-request script will execute before the main request is sent.
- View Logs: Use
console.log()in your script to output debug information. Open the “Console” (View > Show Postman Console) to see the logs.
5. Debugging Tips
- Check Variable Values: Use
console.log(pm.environment.get("variable_name"))to verify variables are set correctly. - Error Handling: Wrap
pm.sendRequest()in a try-catch block to handle errors (e.g., network issues). - Postman Console: Always check the console for script errors—it’s the first place to look when things go wrong.
By following these steps, you can effectively use pre-request scripts in Postman on Ubuntu to automate API testing and streamline workflows. Pre-request scripts are a powerful tool for dynamic request preparation, and mastering them will significantly improve your API testing efficiency.
以上就是关于“Postman在Ubuntu上如何使用Pre-request Script”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm