linux

Linux Postman如何使用Pre-request Script

小樊
55
2025-09-22 16:16:24
栏目: 智能运维

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:

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.

b. Modifying Request Configurations

Use pm.request to dynamically change request headers, URL parameters, or body before sending.

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


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.

0
看了该问题的人还看了