ubuntu

Postman在Ubuntu上如何使用Pre-request Script

小樊
53
2025-09-02 11:52:14
栏目: 智能运维

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:

2. Access Pre-request Script Editor

To add a pre-request script to a request:

  1. Open Postman and select an existing request or create a new one (click “+” in the top-left corner).
  2. 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

5. Debugging Tips

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.

0
看了该问题的人还看了