Postman登录/注册时无法用测试脚本设置JWT令牌为环境变量
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
jwtvariable 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:
- Click the eye icon next to the environment dropdown in the top-right.
- In the "Manage Environments" modal, select your target environment.
- Look for the
jwtvariable 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

