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

Postman登录/注册时无法用测试脚本设置JWT令牌为环境变量

Fix: JWT Token Not Being Set as Environment Variable in Postman Tests

Let's work through why your JWT token isn't saving to the environment variable as expected. Here are the most common fixes and verification steps:

1. Switch to the Updated Postman API (Most Likely Root Cause)

The postman.setEnvironmentVariable() method is deprecated in modern Postman versions. You need to use the current pm API instead. Replace your test script with this:

pm.environment.set("jwt", pm.response.json().token);

This is the officially supported way to set environment variables now, and the old method often fails in recent Postman releases.

2. Confirm Your Script is in the Correct Tab

Make sure you’ve added the script to the Tests tab of your request, not the Pre-request Script tab. The Pre-request Script runs before your request is sent (so there’s no response data to parse yet), while the Tests tab executes after the request completes—when the response with your token is available.

3. Verify You’ve Selected the Right Environment

  • Check the top-right corner of Postman: there’s a dropdown menu for environments.
  • Ensure you’ve selected the environment where you want the jwt variable stored. If you leave it set to "No Environment", the variable will save but won’t be accessible to other requests targeting a specific environment.

4. Debug Token Parsing with Console Logs

To confirm the token is being extracted correctly, add a console log to your Tests script:

const responseData = pm.response.json();
console.log("Extracted Token:", responseData.token);
pm.environment.set("jwt", responseData.token);

Then open the Postman Console (go to View > Show Postman Console), send your login/register request, and check if the token appears in the logs. Double-check that the response’s token key is exactly token (case-sensitive)—your sample response uses lowercase, so that should align.

5. Manually Check the Environment Variable

After sending the request:

  1. Click the eye icon next to the environment dropdown in the top-right.
  2. In the "Manage Environments" modal, select your target environment.
  3. Look for the jwt variable in the list—it should show the token value from your response.

Following these steps should get your JWT token saved to the environment variable successfully.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:07:53