You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Postman预请求脚本:批量遍历用户地点列表执行POST请求

Got it, let's figure out how to solve this Postman challenge you're dealing with! You need to send a POST request for each of your 200 user locations—each with its own unique searchLoc field—and you're curious about either looping through the list in one go or using a folder-level pre-request script to repeat the POST 200 times. Here are two practical solutions to get this done:

This is the most stable approach for bulk requests, as it's designed specifically for this kind of iterative task.

  • Step 1: Set up your POST request with variables
    In your request body (assuming JSON format), replace the hardcoded searchLoc value with a variable. For example:

    {
      "searchLoc": "{{locationPayload}}"
    }
    

    Adjust the variable name and structure to match what your backend expects—if searchLoc needs to be an object with code, name, and coordinates, you can structure the variable to hold that full object.

  • Step 2: Prepare your data file
    Take your userLocations array and convert it into a JSON or CSV file that maps to your variable. For JSON, it might look like this:

    [
      {"locationPayload": {"code": "WDC", "name": "Washington", "lat": 38.8976, "lon": -76.0476}},
      {"locationPayload": {"code": "NYC", "name": "New York", "lat": 40.7128, "lon": -74.0060}},
      // Add the remaining 198 entries here
    ]
    
  • Step 3: Run the collection
    Open the Collection Runner, select your request/folder, then under the Data tab, upload your prepared file. Postman will automatically detect the number of iterations needed (200 in your case). Hit "Run"—each iteration will inject a new location into the locationPayload variable and send a unique POST request. You can even enable response saving to review results later.

Solution 2: Folder-Level Pre-Request Script with Environment Variables

If you prefer to handle this via scripts instead of the Runner, you can use environment variables to track your loop progress and trigger requests programmatically.

  • Step 1: Initialize environment variables
    Create three environment variables:

    • locationIndex (set to 0 to start from the first entry)
    • totalLocations (set to 200)
    • You can also store your userLocations array here as a JSON string, or define it directly in the script.
  • Step 2: Add the pre-request script to your folder
    Paste this script into the folder's pre-request editor (adjust the searchLoc structure to match your needs):

    // Define your full list of locations (or pull from environment variable)
    var userLocations = [
      ["WDC","Washington",38.8976,-76.0476],
      ["NYC","New York",40.7128,-74.0060],
      // Fill in all 200 entries here
    ];
    
    // Get current loop index from environment
    let currentIndex = parseInt(pm.environment.get("locationIndex")) || 0;
    
    if (currentIndex < userLocations.length) {
      // Grab the current location data
      const [code, name, lat, lon] = userLocations[currentIndex];
      
      // Build the searchLoc payload (match your backend's expected format)
      const searchLoc = {
        code: code,
        city: name,
        coordinates: `${lat},${lon}`
      };
    
      // Save the payload to an environment variable for the POST request
      pm.environment.set("searchLoc", JSON.stringify(searchLoc));
    
      // Trigger the POST request programmatically
      pm.sendRequest({
        url: pm.request.url.toString(),
        method: 'POST',
        headers: pm.request.headers.toJSON(),
        body: {
          mode: pm.request.body.mode,
          raw: pm.request.body.raw.replace("{{searchLoc}}", JSON.stringify(searchLoc))
        }
      }, (err, res) => {
        if (err) {
          console.error(`Error sending request for ${name}:`, err);
        } else {
          console.log(`Successfully sent request for ${name}`);
        }
      });
    
      // Increment the index for the next iteration
      pm.environment.set("locationIndex", currentIndex + 1);
    } else {
      // Reset index once all requests are done
      pm.environment.set("locationIndex", 0);
      console.log("All 200 location requests have been processed!");
    }
    
  • Step 3: Update your POST request body
    Replace the searchLoc field with the environment variable:

    {
      "searchLoc": {{searchLoc}}
    }
    

    (No quotes around the variable here because it's a JSON object string, which will parse correctly when injected.)

Quick Notes

  • Always test with a small subset of locations first (like 2-3 entries) to make sure the payload structure matches what your backend expects.
  • The Collection Runner is more reliable for large batches (200 requests) since script-based requests can hit execution time limits or rate issues.
  • If using the script method, make sure to reset locationIndex to 0 before starting a new batch.

内容的提问来源于stack exchange,提问作者Jeuke

火山引擎 最新活动