溫馨提示×

Linux Postman如何使用Pre-request Script

小樊
51
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:

  • 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-catch blocks 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.

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女