Pre-request Script in Postman: Essential Guide for Linux Users
Pre-request scripts are JavaScript code snippets executed before sending an HTTP request in Postman. They are crucial for automating dynamic parameter generation, modifying request configurations, and setting up prerequisites (e.g., authentication tokens) for your API tests. Below is a structured guide to using pre-request scripts in Postman on Linux, covering setup, core functionalities, practical examples, and debugging tips.
1. Accessing Pre-request Script in Postman (Linux)
Postman’s Linux version (installed via Snap or .deb package) follows the same interface as other platforms. To add a pre-request script:
- Open your Postman application.
- Create or select a request: Click the “+” button to create a new request or choose an existing one from your history/collections.
- Navigate to the Pre-request Script tab: In the request editor, locate the “Pre-request Script” tab (below the “Tests” tab). This is where you’ll write your JavaScript code.
All pre-request scripts are scoped to the request level by default, but you can also define them at the collection or folder level (executed in order: collection > folder > request).
2. Core Functionalities of Pre-request Scripts
Pre-request scripts leverage the pm (Postman) object to interact with requests, variables, and the environment. Below are the most commonly used features:
a. Variable Management
Postman supports environment variables, global variables, collection variables, and local variables (script-scoped). Use these to store and retrieve dynamic values (e.g., tokens, timestamps) across requests.
- Get a variable:
const envVar = pm.environment.get("variable_name"); // Environment variable const globalVar = pm.globals.get("global_variable"); // Global variable const collectionVar = pm.collectionVariables.get("collection_var"); // Collection variable - Set a variable:
pm.environment.set("timestamp", new Date().getTime()); // Set environment variable pm.globals.set("api_key", "12345-abcde"); // Set global variable - Remove a variable:
pm.environment.unset("old_variable"); // Remove environment variable
b. Modifying Request Configurations
Use pm.request to dynamically change request headers, URL parameters, or body before sending.
- Add a request header:
pm.request.headers.add({ key: "Authorization", value: "Bearer " + pm.environment.get("token") }); - Set a URL parameter:
pm.request.url.query.add({ key: "userId", value: pm.variables.get("userId") }); - Modify request body (raw JSON):
pm.request.body.raw = JSON.stringify({ key: "value", timestamp: pm.environment.get("timestamp") });
c. Sending Secondary Requests
Use pm.sendRequest to call external APIs (e.g., to fetch an authentication token) before the main request. This is useful for chained API workflows.
pm.sendRequest({
url: "https://api.example.com/auth",
method: "POST",
body: {
mode: "raw",
raw: JSON.stringify({ username: "test", password: "pass" })
}
}, (err, response) => {
if (err) console.error(err);
else {
const token = response.json().access_token;
pm.environment.set("auth_token", token); // Store token for main request
}
});
d. Using Built-in Libraries
Postman includes libraries like crypto-js (for encryption) and moment.js (for date formatting). Load them using pm.require():
const moment = pm.require('moment');
const timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
pm.environment.set("current_time", timestamp);
e. Debugging with Console Logs
Use console.log() to output variable values or script flow to the Postman Console (View > Show Postman Console). This helps troubleshoot issues like missing variables or incorrect script logic.
console.log("Timestamp:", pm.environment.get("timestamp"));
console.log("Auth Token:", pm.environment.get("auth_token"));
3. Practical Examples for Linux Users
Here are real-world scenarios where pre-request scripts save time:
Example 1: Generate a Random User ID
Create a unique user ID for each request to avoid conflicts in testing:
const userId = Math.floor(Math.random() * 1000000); // Random number between 0-999999
pm.environment.set("userId", userId); // Store in environment variable
console.log("Generated User ID:", userId);
Example 2: Add Authorization Header
Automatically attach a Bearer token (from an environment variable) to every request:
const token = pm.environment.get("auth_token");
if (token) {
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
} else {
console.warn("Auth token not found!");
}
Example 3: Encrypt Request Body with RSA
Encrypt sensitive data (e.g., user credentials) using a public key before sending:
const crypto = pm.require('crypto-js');
const publicKey = pm.environment.get("public_key");
const requestBody = { username: "testuser", password: "securepass123" };
// Convert request body to string and encrypt
const encryptedBody = crypto.AES.encrypt(JSON.stringify(requestBody), publicKey).toString();
pm.request.body.raw = JSON.stringify({ data: encryptedBody });
console.log("Encrypted Body:", encryptedBody);
Example 4: Validate Parameters Before Sending
Check if required parameters exist to prevent invalid requests:
const amount = pm.request.body.formdata.find(param => param.key === "amount");
if (amount && parseFloat(amount.value) < 1.0) {
throw new Error("Payment amount must be at least 1.0");
}
console.log("Amount validation passed:", amount.value);
4. Debugging and Optimization Tips
- Use the Postman Console: Always check the console for logs (
console.log()) to verify script execution and variable values. - Error Handling: Wrap scripts in
try-catchblocks to handle exceptions gracefully:try { const token = pm.environment.get("token"); if (!token) throw new Error("Token not found!"); pm.request.headers.add({ key: "Authorization", value: "Bearer " + token }); } catch (err) { console.error("Pre-request error:", err.message); } - Test Incrementally: Run scripts step-by-step using breakpoints (right-click in the script editor and select “Add Breakpoint”) to debug complex logic.
- Scope Variables Properly: Use environment variables for values shared across requests, and local variables for temporary data within a single script.
By mastering pre-request scripts, you can automate repetitive tasks, reduce manual errors, and create more robust API tests in Postman—regardless of your operating system. The Linux version behaves identically to other platforms, so focus on learning the JavaScript API and leveraging Postman’s built-in tools to streamline your workflow.
以上就是关于“Linux Postman如何使用Pre-request Script”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm