Postman预请求脚本中能否以编程方式设置集合变量?
Absolutely—you can programmatically set and retrieve collection-scoped variables in Postman pre-request scripts, even if the official docs don’t highlight this as prominently as they do global or environment variables. I’ve had to dig into this myself before, so let’s break down how it works:
- Set a collection variable: Use the
pm.collectionVariables.set()method to define or update a variable. Here’s a quick example:// Set a collection variable named "currentTimestamp" to the current time pm.collectionVariables.set("currentTimestamp", Date.now().toString()); - Get a collection variable: To fetch the value later (either in the same pre-request script, a test script, or even in request URLs/body), use
pm.collectionVariables.get():// Retrieve the timestamp variable and log it const timestamp = pm.collectionVariables.get("currentTimestamp"); console.log(`Request timestamp: ${timestamp}`);
This functionality works identically in both pre-request and test scripts. A quick reminder on scope: these variables are tied exclusively to your active collection—they won’t be accessible when working with other collections, which sets them apart from global variables (available across all your Postman work) and environment variables (tied to a selected environment profile).
If you need to bulk-update collection variables, you can also use pm.collectionVariables.replaceIn() to swap values across the entire set, but the set() method is the go-to for most single-variable use cases.
内容的提问来源于stack exchange,提问作者dmorrow

