You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Postman预请求脚本中能否以编程方式设置集合变量?

Can You Programmatically Set Collection-Scope Variables in Postman Pre-Request Scripts?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:12:51